Java 使用GraalVM(JDK21)+ gradle 进行 AOT编译为exe文件

1 篇文章 0 订阅

最近graalvm 很火,提供了native-image aot 编译。
网上教程很多,都是graalvm+maven ,拜托都什么年代了还用maven,spring都默认gradle 了,搜了一圈没有。在此我出了此教程,以作记录,应该是csdn 第一篇 gradle+graalvm +aot 编译的教程吧

1.下载graalvm
graalvm 包含了jvm, 可以用来进行jit 及时编译,也可以用来进行aot 编译,aot 编译后会生成二进制机器码不依赖于jvm 运行。
下载链接:graalvm 官方链接
在这里插入图片描述

2.下载gradle 8.10
下载链接:gradle 官方链接
在这里插入图片描述
3.安装window 必要的编译工具
官方教程:window 基础编译工具,对着教程来配置就行
在这里插入图片描述

4.创建项目
新建1个java + gradle 项目
在这里插入图片描述
5.新建HelloWorld.java
在这里插入图片描述

package org.ch;

/**
 * 2024-08-29
 */
public class HelloWorld {
    public static void main(String[] args) throws InterruptedException {
        //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
        // to see how IntelliJ IDEA suggests fixing it.
        System.out.printf("Hello and welcome!");

        for (int i = 1; i <= 5; i++) {
            System.out.println("i = " + i);
        }
        Thread.sleep(10000);
    }
}
  1. gradle 文件 (重点,添加graalvm 插件,否则无法aot 编译)
    build.gradle.kts
plugins {
    id("java")
    id("org.graalvm.buildtools.native") version "0.10.2"
}

group = "org.ch"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
    maven {
        url = uri("https://raw.githubusercontent.com/graalvm/native-build-tools/snapshots")
    }
    gradlePluginPortal()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.10.0"))
    testImplementation("org.junit.jupiter:junit-jupiter")
}


graalvmNative {
    binaries {
        named("main") {
            imageName.set("Hello-word")
            mainClass.set("org.ch.HelloWorld")
            buildArgs.add("-O4")
        }
        named("test") {
            buildArgs.add("-O0")
        }
    }
    binaries.all {
        buildArgs.add("--verbose")
    }
}


tasks.test {
    useJUnitPlatform()
}

项目运行成功
在这里插入图片描述

7.aot 编译(重点)
双击nativeBuild
在这里插入图片描述
本地电脑耗时35s 编译成功,并生成exe 可执行文件,大小17.4M
电脑cpu i7-13700h ,64G内存

在这里插入图片描述

在这里插入图片描述

GraalVM Native Image: Generating 'Hello-word' (executable)...
========================================================================================================================
For detailed information and explanations on the build output, visit:
https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/BuildOutput.md
------------------------------------------------------------------------------------------------------------------------
[1/8] Initializing...                                                                                    (4.7s @ 0.17GB)
 Java version: 21.0.4+8-LTS, vendor version: Oracle GraalVM 21.0.4+8.1
 Graal compiler: optimization level: 4, target machine: x86-64-v3, PGO: ML-inferred
 C compiler: cl.exe (microsoft, x64, 19.41.34120)
 Garbage collector: Serial GC (max heap size: 80% of RAM)
 1 user-specific feature(s):
 - com.oracle.svm.thirdparty.gson.GsonFeature
------------------------------------------------------------------------------------------------------------------------
Build resources:
 - 26.49GB of memory (41.6% of 63.73GB system memory, determined at start)
 - 20 thread(s) (100.0% of 20 available processor(s), determined at start)
[2/8] Performing analysis...  [*****]                                                                    (4.5s @ 0.37GB)
    3,144 reachable types   (71.1% of    4,420 total)
    3,708 reachable fields  (49.6% of    7,483 total)
   15,605 reachable methods (45.7% of   34,183 total)
    1,051 types,    36 fields, and   530 methods registered for reflection
       61 types,    51 fields, and    52 methods registered for JNI access
        1 native library: version
[3/8] Building universe...                                                                               (1.0s @ 0.36GB)
[4/8] Parsing methods...      [*]                                                                        (1.3s @ 0.37GB)
[5/8] Inlining methods...     [***]                                                                      (0.3s @ 0.46GB)
[6/8] Compiling methods...    [****]                                                                    (16.9s @ 1.09GB)
[7/8] Layouting methods...    [*]                                                                        (1.8s @ 0.41GB)
[8/8] Creating image...       [*]                                                                        (1.3s @ 0.55GB)
  10.22MB (58.73%) for code area:     7,087 compilation units
   7.00MB (40.20%) for image heap:  102,441 objects and 75 resources
 189.52kB ( 1.06%) for other data
  17.40MB in total
------------------------------------------------------------------------------------------------------------------------
Top 10 origins of code area:                                Top 10 object types in image heap:
   7.50MB java.base                                            2.27MB byte[] for code metadata
   1.86MB svm.jar (Native Image)                               1.28MB byte[] for java.lang.String
 325.77kB com.oracle.svm.svm_enterprise                      771.61kB java.lang.String
 242.27kB java.logging                                       530.41kB java.lang.Class
  55.49kB org.graalvm.nativeimage.base                       336.54kB byte[] for general heap data
  52.09kB org.graalvm.collections                            235.63kB java.util.HashMap$Node
  45.71kB jdk.proxy2                                         154.34kB byte[] for embedded resources
  43.85kB jdk.proxy1                                         147.53kB byte[] for reflection metadata
  28.71kB jdk.internal.vm.ci                                 147.38kB com.oracle.svm.core.hub.DynamicHubCompanion
  27.08kB jdk.internal.vm.compiler                           145.88kB char[]
  15.98kB for 4 more packages                                  1.04MB for 846 more object types
                              Use '-H:+BuildReport' to create a report with more details.
------------------------------------------------------------------------------------------------------------------------
Security report:
 - Binary includes Java deserialization.
 - Use '--enable-sbom' to embed a Software Bill of Materials (SBOM) in the binary.
------------------------------------------------------------------------------------------------------------------------
Recommendations:
 PGO:  Use Profile-Guided Optimizations ('--pgo') for improved throughput.
 INIT: Adopt '--strict-image-heap' to prepare for the next GraalVM release.
 HEAP: Set max heap for improved and more predictable memory usage.
 CPU:  Enable more CPU features with '-march=native' for improved performance.
 QBM:  Use the quick build mode ('-Ob') to speed up builds during development.
------------------------------------------------------------------------------------------------------------------------
                        2.6s (7.9% of total time) in 325 GCs | Peak RSS: 1.91GB | CPU load: 9.14
------------------------------------------------------------------------------------------------------------------------
Produced artifacts:
 D:\me\code\graalvm-demo\graalvm-demo\build\native\nativeCompile\Hello-word.exe (executable)
========================================================================================================================
Finished generating 'Hello-word' in 32.4s.
[native-image-plugin] Native Image written to: D:\me\code\graalvm-demo\graalvm-demo\build\native\nativeCompile

> Task :nativeBuild
Task nativeBuild is deprecated. Use nativeCompile instead.

BUILD SUCCESSFUL in 35s
5 actionable tasks: 4 executed, 1 up-to-date
21:55:53: Execution finished 'nativeBuild'.

8.运行exe
在这里插入图片描述
占用内存1.1M
在这里插入图片描述

8.总结:
我们看下各项指标:
编译耗时35s
文件大小17M
占用内存 1.1M
启动速度0.1s
graalvm aot 编译的优缺点:
优点:启动速度非常快,占用内存非常小
缺点:打包的可执行文件大,编译耗时长

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值