GraalVM Native Image

GraalVM Native Image allows you to ahead-of-time compile Java code to a standalone executable, called a native image. This executable includes the application, the libraries, the JDK and does not run on the Java VM, but includes necessary components like memory management and thread scheduling from a different virtual machine, called “Substrate VM”. Substrate VM is the name for the runtime components (like the deoptimizer, garbage collector, thread scheduling etc.). The resulting program has faster startup time and lower runtime memory overhead compared to a Java VM.

Native Image Generator or native-image is a utility that processes all the classes of your application and their dependencies, including those from the JDK. It statically analyses these classes to determine which classes and methods are reachable and used during application execution. Then it passes all this reachable code as the input to the GraalVM compiler which ahead-of-time compiles it to the native binary.

GraalVM native-image supports JVM-based languages, e.g., Java, Scala, Clojure, Kotlin. The resulting native image can, optionally, execute dynamic languages like Ruby, R, or Python, but it does not pre-compile their code itself. Polyglot embeddings can also be compiled ahead-of-time. To inform native-image of guest languages used by an application, specify --language:<languageId> for each guest language used (e.g., --language:js).

Important: GraalVM Native Image is available as an early adopter plugin. This means its functionality is subject to change while its specification is being developed by the Java community.

Install Native Image

Starting from GraalVM 19.0, Native Image was extracted from the base distribution. This functionality can be added to the core installation with GraalVM Updater tool in a similar way as other additional components by running:

gu install native-image

After this additional step, the native-image executable will be in the bin directory, as for the previous releases.

Take a look at the native image generation or compiling a Java and Kotlin app ahead-of-time samples.

Prerequisites

For compilation native-image depends on the local toolchain, so please make sure: glibc-devel, zlib-devel (header files for the C library and zlib) and gcc are available on your system.

Another prerequisite to consider is the maximum heap size. Physical memory for running a JVM-based application may be insufficient to build a native image. For server-based image building we allow to use 80% of the reported physical RAM for all servers together, but never more than 14GB per server (for exact details please consult the native-image source code). If you run with --no-server option, you will get the whole 80% of what is reported as physical RAM as the baseline. This mode respects -Xmx arguments additionally.

Image Generation Options

The native-image command line needs to provide the class path for all classes using the familiar option from the java launcher: -cp is followed by a list of directories or .jar files, separated by :. The name of the class containing the main method is the last argument; or you can use -jar and provide a .jar file that specifies the main method in its manifest. The syntax of the native-image command is:

  • native-image [options] class to build an executable file for a class in the current working directory. Invoking it executes the native-compiled code of that class.

  • native-image [options] -jar jarfile to build an image for a jar file.

There is a command-line help available. Run native-image --help to get commands overview and native-image --help-extra to print help on non-standard options.

You may provide additional options to the native image building:

  • -cp and --class-path <class search path of directories and zip/jar files> help to search for class files through separated list of directories, JAR archives, and ZIP archives;

  • -D<name>=<value> sets a system property for the JVM running the image generator;

  • -J<flag> passes <flag> directly to the JVM running the image generator;

  • -O<level> 0 – no optimizations, 1 – basic optimizations (default);

  • -ea and -da enables or disables assertions in the generated image;

  • --allow-incomplete-classpath allows image building with an incomplete class path and reports type resolution errors at run time when they are accessed the first time, instead of during image building;

  • --auto-fallback builds a stand-alone image if possible, which is a default setting, --no-fallback builds a stand-alone image or reports a failure, and --force-fallback forces building of a fallback image;

  • --enable-all-security-services adds all security service classes to the generated image;

  • --enable-http or --enable-https enables http or https support in the generated image;

  • --enable-url-protocols provides a list of comma separated URL protocols to enable;

  • --features provides a comma-separated list of fully qualified feature implementation classes;

  • --initialize-at-build-time=<comma separated list of class/package names> initializes classes and implicitly all of their superclasses during image building;

  • --initialize-at-run-time=<comma separated list of class/package names> initializes classes and implicitly all of their superclasses at run time and not during image building;

  • --report-unsupported-elements-at-runtime reports usage of unsupported methods and fields at run time when they are accessed the first time, instead of as an error during image building;

  • --shared builds shared library;

  • --static builds statically linked executable (requires static libc and zlib) (since 1.0-rc2);

  • --verbose enables verbose output.

Important: The following native image options are available only with GraalVM Enterprise Edition:

  • -g enables the debugging info generation;

  • --pgo-instrument builds an instrumented native image with profile-guided optimization data collected in the default.iprof file, if nothing else is specified;

  • --pgo provides a comma-separated list of files from which to read the data collected for profile-guided optimization of ahead-of-time compiled code.

Macro Options

Macro-options are mainly helpful for polyglot capabilities of native images:

  • --language:nfi to make Truffle Native Function Interface language available;

  • --language:regex to make Truffle Regular Expression engine available that exposes regular expression functionality in GraalVM supported languages;

  • --language:python to make sure Python is available as a language for the image;

  • --language:llvm to make sure LLVM bitcode is available for the image;

  • --language:js to make sure JavaScript is available as a language for the image;

  • --language:ruby to make sure Ruby is available as a language for the image;

  • --language:R to make sure R is available as a language for the image;

  • --tool:chromeinspector adds debugging support to a Truffle framework based language image;

  • --tool:profiler adds profiling support to a Truffle framework based language image.

Please note, the --language:python, --language:ruby and --language:R polyglot macro options become available once the corresponding languages engines are added to the base GraalVM installation with GraalVM Updater tool:

gu install python
gu install ruby
gu install R

Non-standard Options

Get acquainted with the non-standard native image building options, that are subject to change through a deprecation cycle:

  • --no-server tells to not use server-based image building;

  • --server-list lists current image-build servers;

  • --server-list-details lists current image-build servers with more details;

  • --server-cleanup removes stale image-build servers entries;

  • --server-shutdown shuts down image-build servers under current session ID;

  • --server-shutdown-all shuts down all image-build servers;

  • --server-session=<custom-session-name> uses custom session name instead of system provided session ID of the calling process;

  • --verbose-server enables verbose output for image-build server handling.

Server-side Options

  • --debug-attach[=<port>] attaches to debugger during image building (default port is 8000);

  • --dry-run outputs the command line that would be used for image building;

  • --expert-options lists image build options for experts;

  • --expert-options-all lists all image build options for experts (to be used at your own risk);

  • --configurations-path <search path of option-configuration directories> a separated list of directories to be treated as option-configuration directories;

  • -V<key>=<value> provides values for placeholders in native-image.properties files.

If the environment variable NATIVE_IMAGE_CONFIG_FILE is set to a Java properties file, a native image will use the defaults defined in there on each invocation.

Here is an example of configuration file (saved as ~/.native-image/default.properties) :

NativeImageArgs = --configurations-path /home/user/custom-image-configs \
                  -O1

If the user has a configuration file and export NATIVE_IMAGE_CONFIG_FILE=$HOME/.native-image/default.properties in ~/.bash_profile, every time the native image gets used, it will implicitly use the arguments specified as NativeImageArgs, plus the arguments specified on command line.

For a more comprehensive list of options please check the documentation on Github.

Important: Python source code or LLVM bitcode interpreted or compiled with GraalVM Community Edition will not have the same security characteristics as the same code interpreted or compiled using GraalVM Enterprise Edition. There is a GraalVM string embedded in each image that allows to figure out the version and variant of the base (Community or Enterprise) used to build an image. The following command will query that information from an image:

strings <path to native-image exe or shared object> | grep com.oracle.svm.core.VM

Assuming you have a Java class file EmptyHello.class containing an empty main method and have generated an empty shared object emptyhello with GraalVM Native Image Generator utility of it:

$ native-image -cp hello EmptyHello
Build on Server(pid: 11228, port: 41223)
[emptyhello:11228]    classlist:     149.59 ms
...

If you do not know what GraalVM distribution is set to the PATH environment variable, how to determine if a native image was compiled with Community or Enterprise Edition? Run this command:

$ strings emptyhello | grep com.oracle.svm.core.VM

The expected output should match the following:

com.oracle.svm.core.VM GraalVM 19.0.0 CE

Generating Heap Dumps

GraalVM also supports monitoring and generating heap dumps of the Native Image processes. This functionality is available in the Enterprise Edition of GraalVM. It is not available in the Community Edition of GraalVM.

To find out more about generating heap dumps of the native image processes, refer to the step-by-step documentation.

Limitations of AOT Compilation

To achieve such aggressive ahead-of-time optimizations, we run an aggressive static analysis that requires a closed-world assumption. We need to know all classes and all bytecodes that are reachable at run time. Therefore, it is not possible to load new classes that have not been available during ahead-of-time-compilation.

For a more detailed description of which features of Java are not supported by the native images or supported partially please refer to the documentation on the GitHub. And if you are interested in learning about the support for Java reflection, there is a separate document for Java reflection support.

Operational Information for Native Images

When does it make sense to run in a Native Image instead of the JVM?

  • When startup time and memory footprint is important.
  • When you want to embed Java code with existing C/C++ applications

What tools work with Native Image: debugger, profilers? How to use them?

  • The community version does not support DWARF information. The enterprise version supports all native tools that rely on DWARF information, like debuggers (gdb) and profilers (VTune).