GraalVMのNative Imageを試す

GraalVMのNative Imageを試したときのメモ。

ソースコード

public class HelloWorld {
    static {
        System.out.println("Static initialization");
    }
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

Demo

DockerのGraalVMを使う場合

カレントディレクトリにHelloWorld.javaを置いて、コンテナを起動する

% docker run -v `pwd`:/tmp -it oracle/graalvm-ce bash

native-imageコマンドをインストールする

bash-4.2# gu install native-image

Javaコードをコンパイルする

bash-4.2# cd tmp
bash-4.2# mkdir out
bash-4.2# javac -d out/ HelloWorld.java

Native Imageを生成して実行する

bash-4.2# native-image -cp out/ HelloWorld
Build on Server(pid: 113, port: 42993)
[helloworld:113]    classlist:     208.02 ms
[helloworld:113]        (cap):     812.16 ms
[helloworld:113]        setup:   1,094.60 ms
[helloworld:113]   (typeflow):   2,439.05 ms
[helloworld:113]    (objects):   2,606.36 ms
[helloworld:113]   (features):     118.09 ms
[helloworld:113]     analysis:   5,267.27 ms
[helloworld:113]     (clinit):      61.06 ms
[helloworld:113]     universe:     190.47 ms
[helloworld:113]      (parse):     232.66 ms
[helloworld:113]     (inline):     653.02 ms
[helloworld:113]    (compile):   1,515.33 ms
[helloworld:113]      compile:   2,571.28 ms
[helloworld:113]        image:     216.05 ms
[helloworld:113]        write:     338.25 ms
[helloworld:113]      [total]:  10,010.49 ms
bash-4.2# time ./helloworld 
Static initialization
Hello world!

real    0m0.015s
user    0m0.001s
sys 0m0.003s

--initialize-at-build-time を指定した場合

bash-4.2# native-image --initialize-at-build-time=HelloWorld -cp out/ HelloWorld
Build on Server(pid: 113, port: 42993)
[helloworld:113]    classlist:     161.72 ms
Static initialization
[helloworld:113]        (cap):     784.22 ms
[helloworld:113]        setup:   1,035.82 ms
[helloworld:113]   (typeflow):   2,543.74 ms
[helloworld:113]    (objects):   2,808.22 ms
[helloworld:113]   (features):     108.06 ms
[helloworld:113]     analysis:   5,550.17 ms
[helloworld:113]     (clinit):      61.06 ms
[helloworld:113]     universe:     226.54 ms
[helloworld:113]      (parse):     238.89 ms
[helloworld:113]     (inline):     757.67 ms
[helloworld:113]    (compile):   1,525.27 ms
[helloworld:113]      compile:   2,684.69 ms
[helloworld:113]        image:     213.52 ms
[helloworld:113]        write:     328.43 ms
[helloworld:113]      [total]:  10,317.39 ms
bash-4.2# time ./helloworld 
Hello world!

real    0m0.016s
user    0m0.000s
sys 0m0.005s

Macで実行する場合

SDKMANでGraalVMをインストールする

% sdk install java 20.1.0.r11-grl
% sdk use java 20.1.0.r11-grl

native-imageコマンドをインストールする

% gu install native-image 

Javaコードをコンパイルする

% javac HelloWorld.java  

Native Imageを生成して実行する

% native-image HelloWorld
% ./helloworld
Static initialization
Hello world!