GraalVM Native Image

GraalVM Native Image allows you to ahead-of-time compile Java code to a standalone executable, calleda native image. This executable includes the application classes, classesfrom its dependencies, runtime library classes from JDK and statically linkednative code from JDK. It does not run on the Java VM, but includes necessarycomponents like memory management and thread scheduling from a different virtualmachine, called “Substrate VM”. Substrate VM is the name for the runtimecomponents (like the deoptimizer, garbage collector, thread scheduling etc.).The resulting program has faster startup time and lower runtime memory overheadcompared 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 classesto determine which classes and methods are reachable and used during applicationexecution. Then it passes all this reachable code as the input to the GraalVMcompiler 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 dynamiclanguages like JavaScript, Ruby, R, or Python, but it does not pre-compile their codeitself. Polyglot embeddings can also be compiled ahead-of-time. To informnative-image of guest languages used by an application, specify—language:<languageId> for each guest language used (e.g., —language:js).

Warning: GraalVM Native Image isavailable as an Early Adopter technology.

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 utility in a similar way as other additional components.

For GraalVM Enterprise Edition users, download the Native Image component JARfile from Oracle Technology Network and install itby running gu -L install component.jar, where -L option, equivalent to—local-file or —file, tells to install a component from a downloaded archive.

For GraalVM Community Edition users, install a component from the GitHub catalog byits name gu install native-image.

After this additional step, the native-image executable will become available inthe 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 makesure: 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 forrunning a JVM-based application may be insufficient to build a native image. Forserver-based image building we allow to use 80% of the reported physical RAM forall servers together, but never more than 14GB per server (for exact detailsplease consult the native-image source code). If you run with —no-serveroption, you will get the whole 80% of what is reported as physical RAM as thebaseline. This mode respects -Xmx arguments additionally.

Image Generation Options

The native-image command line needs to provide the class path for all classesusing the familiar option from the java launcher: -cp is followed by a listof directories or .jar files, separated by :. The name of the class containingthe main method is the last argument; or you can use -jar and provide a .jarfile 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 thecurrent working directory. Invoking it executes the native-compiled code of thatclass.

  • 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 getcommands overview and native-image —help-extra to print help on non-standardoptions.

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=<fqcn> 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 a shared library

  • —static builds a statically linked executable. This option prevents linking against shared libraries. This requires the static libc and libstdc++ libraries to be available on the host system. Warning: On systems other than Linux, this option has no effect

  • —verbose makes image building output more verbose

  • -g enables the debugging info generation. Warning: The option is available only with GraalVM Enterprise Edition

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:js to make sure JavaScript is available as a language for the image

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

  • —language:python to make sure Python 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 installed to the base GraalVM distribution.

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

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

Native Image Configuration

The native-image tool supports a wide range of options to configure a native image build process.

A recommended way to provide configuration is to embed anative-image.properties file into a project jar file. The Native Image toolwill automatically pick up all configuration options provided anywhere below theresource location META-INF/native-image/ and use it to constructnative-image command line arguments.

To avoid a situation when constituent parts of a non-trivial project are builtwith overlapping configurations, we recommend to use “subdirectories” withinMETA-INF/native-image. That way a jar file built from multiple maven projectscannot suffer from overlapping native-image configurations. For example:

  • foo.jar has its configurations in META-INF/native-image/foo_groupID/foo_artifactID
  • bar.jar has its configurations in META-INF/native-image/bar_groupID/bar_artifactID

A jar file that contains foo and bar will then contain both configurationswithout conflicting with one another. Therefore the recommended layout forstoring native-image configuration data in jar files is the following:

  1. META-INF/
  2. └── native-image
  3. └── groupID
  4. └── artifactID
  5. └── native-image.properties

Note that the use of ${.} in a native-image.properties file expands to theresource location that contains that exact configuration file. This can beuseful if the native-image.properties file wants to refer to resources withinits “subfolder”, for example,-H:SubstitutionResources=${.}/substitutions.json.

By having such a composable native-image.properties file, building an imagedoes not require any additional arguments specified on command line. It issufficient to just run the following command:

  1. $JAVA_HOME/bin/native-image -jar target/<name>.jar

To debug which configuration data gets applied for the image building use native-image—verbose. This will show from where native-image picks up theconfigurations to construct the final composite configuration command lineoptions for the image builder.

  1. $ native-image --verbose -jar build/basic-app-0.1-all.jar
  2. Apply jar:file://~/build/basic-app-0.1-all.jar!/META-INF/native-image/io.netty/common/native-image.properties
  3. Apply jar:file://~/build/basic-app-0.1-all.jar!/META-INF/native-image/io.netty/buffer/native-image.properties
  4. Apply jar:file://~/build/basic-app-0.1-all.jar!/META-INF/native-image/io.netty/transport/native-image.properties
  5. Apply jar:file://~/build/basic-app-0.1-all.jar!/META-INF/native-image/io.netty/handler/native-image.properties
  6. Apply jar:file://~/build/basic-app-0.1-all.jar!/META-INF/native-image/io.netty/codec-http/native-image.properties
  7. ...
  8. Executing [
  9. <composite configuration command line options for the image builder>
  10. ]

Typical examples of META-INF/native-image based native image configuration can be found in Native Image configuration examples.

Properties File Format

A native-image.properties file is a regular Java properties file that can beused to specify native image configurations. The following properties aresupported.

Args

Use this property if your project requires custom native-image command line options to build correctly. For example, the native-image-configure-examples/configure-at-runtime-example has Args = —initialize-at-build-time=com.fasterxml.jackson.annotation.JsonProperty$Access in its native-image.properties file to ensure the class com.fasterxml.jackson.annotation.JsonProperty$Access gets initialized at image built time.

JavaArgs

Sometimes it can be necessary to provide custom options to the JVM that runs theimage builder. The JavaArgs property can used in this case.

ImageName

This property can be used to specify a user-defined name for the image. IfImageName is not used, a name gets automatically chosen:

  • native-image -jar <name.jar> has a default image name <name>
  • native-image -cp … fully.qualified.MainClass has a default image name fully.qualified.mainclass

Note that using ImageName does not prevent the user to override the name later via command line. For example, if foo.bar contains ImageName=foo_app,

  • native-image -jar foo.bar generates the image foo_app but
  • native-image -jar foo.bar application generates the image application.

Order of Arguments Evaluation

The arguments passed to native-image are evaluated left-to-right. This alsoextends to arguments that get passed indirectly via META-INF/native-imagebased native-image configuration. Suppose you have a jar file that containsnative-image.properties with Args = -H:Optimize=0. Then by using the-H:Optimize=2 option after -cp <jar-file> you can override the setting thatcomes from the jar file.

Specifying Default Options for Native Image

If there is a need to pass some options for every image build unconditionally, forexample, to always generate an image in verbose mode (—verbose), we canmake use of the NATIVE_IMAGE_CONFIG_FILE environment variable.If it is set to a Java properties file, the Native Image builder will use thedefault setting defined in there on each invocation. We have to write aconfiguration file and exportNATIVE_IMAGE_CONFIG_FILE=$HOME/.native-image/default.properties in~/.bash_profile. Every time native-image gets used, it will implicitly usethe arguments specified as NativeImageArgs, plus the arguments specified on thecommand line. Here is an example of a configuration file, saved as~/.native-image/default.properties:

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

Runtime vs Build Time Initialization

Building your application into a native image allows you to decide which partsof your application should be run at image build time and which parts have torun at image runtime.

Since GraalVM 19.0 all class-initialization code (static initializers and staticfield initialization) of the application you build an image for will be executedat image runtime by default. Sometimes it is beneficial to allow classinitialization code to get executed at image build time for faster startup (e.g.if some static fields get initialized to runtime independent data). This can becontrolled with the following native-image options:

  • —initialize-at-build-time=<comma-separated list of packages and classes>
  • —initialize-at-run-time=<comma-separated list of packages and classes>

In addition to that we allow arbitrary computations at built time that can be put into ImageSingletons that areaccessible at image runtime. For more information please have a look at Native Image configuration examples.

To learn more on the topic, continue reading on Application Initialization at Build Time.

Integration with Maven

To simplify the generation of native images, GraalVM Native Image now works outof Maven with the Native Image Maven Plugin.

As demonstrated in the Native Image configuration examples, one can build a native image directly with Mavenusing the mvn package command without running the native-image tool as aseparate step. It is sufficient to add native-image-maven-plugin into the<plugins> section of the pom.xml file:

  1. <plugin>
  2. <groupId>org.graalvm.nativeimage</groupId>
  3. <artifactId>native-image-maven-plugin</artifactId>
  4. <version>${graalvm.version}</version>
  5. <executions>
  6. <execution>
  7. <goals>
  8. <goal>native-image</goal>
  9. </goals>
  10. <phase>package</phase>
  11. </execution>
  12. </executions>
  13. <configuration>
  14. <skip>false</skip>
  15. <imageName>example</imageName>
  16. <buildArgs>
  17. --no-fallback
  18. </buildArgs>
  19. </configuration>
  20. </plugin>

and the org.graalvm.sdk library dependency in the <dependencies> list:

  1. <dependency>
  2. <groupId>org.graalvm.sdk</groupId>
  3. <artifactId>graal-sdk</artifactId>
  4. <version>${graalvm.version}</version>
  5. <scope>provided</scope>
  6. </dependency>

The plugin figures out what jar files it needs to pass to the native image andwhat the executable main class should be. If the heuristics fails with the nomain manifest attribute, in target/<name>.jar error, the main class should bespecified in the <configuration> node of the plugin (see Plugin Customizationsection). When mvn package completes, an executable, generated in the _target_directory of the project, is ready for use.

Warning: As of the GraalVM version 19.3, the Maven <groupId> for the GraalVM NativeImage related artifacts, including the plugin, changes fromcom.oracle.substratevm to org.graalvm.nativeimage(<groupId>org.graalvm.nativeimage</groupId>).

Plugin Customization

When using GraalVM Enterprise Edition as the JAVA_HOMEenvironment, the plugin builds a native image with enterprise features enabled, e.g., an executable will automatically be built with compressed referencesand other optimizations enabled.

It is also possible to customize native-image-maven-plugin within a<configuration> node. The following configurations are available.

  • Configuration parameter <mainClass>. If the execution fails with the no main manifest attribute, in target/<name>.jar error, the main class should be specified. By default the plugin consults several locations in the pom.xml file in the following order to determine what the main class of the image should be:
    • <maven-shade-plugin> <transformers> <transformer> <mainClass>
    • <maven-assembly-plugin> <archive> <manifest> <mainClass>
    • <maven-jar-plugin> <archive> <manifest> <mainClass>
  • Configuration parameter <imageName>. If an image filename is not set explicitly, use parameter <imageName> to provide a custom filename for the image.
  • Configuration parameter <buildArgs>. If you want to pass additional options for the image building, use the <buildArgs> parameter the definition of the plugin. For example, to build a native image with assertions enabled that uses com.test.classname as a main class, add:
  1. <configuration>
  2. <imageName>executable-name</imageName>
  3. <mainClass>com.test.classname</mainClass>
  4. <buildArgs>
  5. --no-fallback
  6. </buildArgs>
  7. <skip>false</skip>
  8. </configuration>

How to Determine What Version of GraalVM an Image Is Generated With?

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 argumentsspecified as NativeImageArgs, plus the arguments specified on command line.

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

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

  1. 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 methodand have generated an empty shared object emptyhello with GraalVM Native Image Generator utility of it:

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

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

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

The expected output should match the following:

  1. com.oracle.svm.core.VM GraalVM 19.3.0.2 CE

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

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

Profile-guided Optimizations

For additional performance gain and higher throughput in GraalVMahead-of-time (AOT) mode, make use of profile-guided optimizations (PGO). WithPGO, you can collect the profiling data in advance and then feed it to theGraalVM native-image utility, which will use this information to optimize theperformance of the resulting binary.

Warning: Profile-guided optimizations (PGO) is a GraalVM Enterprise feature.

In GraalVM versions prior to 19.2.0, a commonly used technique to mitigate themissing just-in-time (JIT) optimization is to gather the execution profiles at one runand then use them to optimize subsequent compilation(s). In other words, oneneeds to create a native image with the —pgo-instrument option to collect theprofile information. The —pgo-instrument builds an instrumented native imagewith profile-guided optimization data collected of AOT compiled codein the default.iprof file, if nothing else is specified. Then you run anexample program, saving the result in default.iprof. Finally, you create asecond native image with —pgo profile.iprof flag that should be significantlyfaster.

Starting from 19.2.0, you can collect profiles while running yourapplication in JIT mode and then use this information to generatea highly-optimized native binary. This maximizes the performance even more.

  • Run a java program in JIT mode with a -Dgraal.PGOInstrument flag to gather the profiling information:
  1. $ java -Dgraal.PGOInstrument=myclass.iprof MyClass
  • Use the collected data to generate a native image:
  1. $ native-image --pgo=myclass.iprof MyClass
  • Run the resulting binary:
  1. $ ./myclass

AOT Compilation Limitations

There is a small portion of Java features are not susceptible to ahead-of-timecompilation, and will therefore miss out on the performance advantages. To beable to build a highly optimized native executable, we run an aggressive staticanalysis that requires a closed-world assumption, which means that all classesand all bytecodes that are reachable at runtime must be known at build time.Therefore, it is not possible to load new data that have not been availableduring ahead-of-time compilation. A more comprehensive list of restrictions can be found in the Native Image Java Limitations document.

Tracing Agent

To overcome some restrictions of GraalVM Native Image and to simplify theconfiguration process, we implemented a tracing agent which records the behaviorof a Java application running on GraalVM or any other compatible JVM thatsupports Java VM Tool Interface (JVMTI). The tracing agent is supported in bothGraalVM Enterprise and Community Editions.

Warning: The tracing agent is part of the GraalVM Native Image component, which must be installed first.

The tracing agent helps to deal with such features as Reflection, Java Native Interface, Class Path Resources, and Dynamic Proxy in the GraalVM environment. It is applicable when the static analysis cannot automatically determine what to put into a native image and undetected usages of these dynamic features need to be provided to the generation process in the form of configuration files. The tracing agent observes the application behavior and builds configuration files when running on the Java HotSpot VM, thus it can be enabled on the command line with the java command:

  1. $JAVA_HOME/bin/java -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/ ...

Please note that -agentlib must be specified before a -jar option or a classname or any application parameters in the java command line.

During execution, the agent interfaces with the JVM to intercept all callsthat look up classes, methods, fields, resources or request proxy accesses. Theagent then generates the jni-config.json, reflect-config.json,proxy-config.json and resource-config.json in the specified outputdirectory. The generated files are stand-alone configuration files in JSONformat which contain all intercepted dynamic accesses.

The generated configuration files can later be supplied to the native-image toolby placing them in a META-INF/native-image/ directory on the class path, forexample, in a JAR file. Not all of those files must be present. When multiplefiles with the same name are found, all of them are included.

Read more about advanced usage of the tracing agent in Assisted Configuration of Native Image Builds document.

Java Reflection Support

Further below we will focus on GraalVM Native Image support of Java Reflection API.

Java Reflection provides the ability to inspect and modify applications runtimebehavior. It allows to inspect a class or an interface, get its methods andfields information, invoke a method, and even create an object of a class atruntime. The Reflection API classes are part of the java.lang.reflect package.

For GraalVM Native Image to handle the Reflection API, in some cases, a reflectionconfiguration has to be provided at image build time. Within aclosed-world assumption approach, an aggressive static analysis can see mostclasses, methods and fields with certainty because they are used directly.However, when the code accesses program elements by name via reflection, theanalysis cannot always determine ahead-of-time what program elements it refersto, and the user’s assistance is then needed to make these elements accessibleat runtime. For example, the analysis can discover all dynamic usages of theClass.forName("java.lang.String").getMethod("hashCode").invoke("Hello!");sequence because only constants are used, but inString.class.getMethod("hashCode".replace('K', 'C')).invoke("Hello!"); itcannot. Where the static analysis fails to access the program elementsreflectively, they must be specified in a configuration file via the option-H:ReflectionConfigurationFiles=. For more details, read our documentation on reflection support.

In the given case, the tracing agent can simplify the configuration process andwrite a reflection configuration file by tracing all reflective lookupoperations on the Java HotSpot VM. The traced operations are Class.forName, Class.getMethod, and Class.getField.

For demonstration purposes, save the following code as ReflectionExample.java file:

  1. import java.lang.reflect.Method;
  2. class StringReverser {
  3. static String reverse(String input) {
  4. return new StringBuilder(input).reverse().toString();
  5. }
  6. }
  7. class StringCapitalizer {
  8. static String capitalize(String input) {
  9. return input.toUpperCase();
  10. }
  11. }
  12. public class ReflectionExample {
  13. public static void main(String[] args) throws ReflectiveOperationException {
  14. String className = args[0];
  15. String methodName = args[1];
  16. String input = args[2];
  17. Class<?> clazz = Class.forName(className);
  18. Method method = clazz.getDeclaredMethod(methodName, String.class);
  19. Object result = method.invoke(null, input);
  20. System.out.println(result);
  21. }
  22. }

This is a simple Java program where non-constant strings for accessing programelements by name must come as external inputs. The main method invokes a methodof a particular class (Class.forName) whose names are passed as command linearguments. Providing any other class or method name on the command line leads toan exception.

Having compiled the example, invoke each method:

  1. $JAVA_HOME/bin/javac ReflectionExample.java
  2. $JAVA_HOME/bin/java ReflectionExample StringReverser reverse "hello"
  3. olleh
  4. $JAVA_HOME/bin/java ReflectionExample StringCapitalizer capitalize "hello"
  5. HELLO

Now we are going to build a native image as regularly, without a reflection configuration file and run a resulting image:

  1. $JAVA_HOME/bin/native-image ReflectionExample
  2. Build on Server(pid: 59625, port: 58819)
  3. [reflectionexample:59625] classlist: 467.66 ms
  4. ...
  5. Warning: Image 'reflectionexample' is a fallback image that requires a JDK for execution (use --no-fallback to suppress fallback image generation).
  6. $ ./reflectionexample

The reflectionexample binary is just a launcher for the Java HotSpot VM, a “fallbackimage” as stated in the warning message. To generate a native image withreflective lookup operations, we will apply the tracing agent to write aconfiguration file to be later feed into the native image generation togetherwith a —no-fallback option.

  • Create a directory META-INF/native-image in the working directory:
  1. mkdir -p META-INF/native-image
  • Enable the agent and pass necessary command line arguments:
  1. $JAVA_HOME/bin/java -agentlib:native-image-agent=config-output-dir=META-INF/native-image ReflectionExample StringReverser reverse "hello"

This command creates a reflection-config.json file which makes the StringReverser class and the reverse() method accessible via reflection. The jni-config.json, proxy-config.json ,and resource-config.json configuration files are written in that directory too.Native Image - 图1

  • Build a native image:
  1. $JAVA_HOME/bin/native-image --no-fallback ReflectionExample

The native image generator automatically picks up configuration files inMETA-INF/native-image directory or subdirectories. However, it is recommendedto have META-INF/native-image location on the class path, either via a JARfile or via the -cp flag. It will help to avoid confusion for IDE users where adirectory structure is defined by the tool.

  • Test the methods, but remember that we have not run the tracing agent twice to create a configurationthat supports both:
  1. $ ./reflectionexample StringReverser reverse "hello"
  2. olleh
  3. $ ./reflectionexample StringCapitalizer capitalize "hello"
  4. Exception in thread "main" java.lang.ClassNotFoundException: StringCapitalizer
  5. at com.oracle.svm.core.hub.ClassForNameSupport.forName(ClassForNameSupport.java:60)
  6. at java.lang.Class.forName(DynamicHub.java:1161)
  7. at ReflectionExample.main(ReflectionExample.java:21)

Neither the tracing agent nor native images generator cannot automatically checkif the provided configuration files are complete. The agent only observes andrecords which values are accessed through reflection so that the same accessesare possible in a native image. You can either manually edit thereflection-config.json file, or re-run the tracing agent to transform theexisting configuration file, or extend it by using config-merge-dir option:

  1. $JAVA_HOME/bin/java -agentlib:native-image-agent=config-merge-dir=META-INF/native-image ReflectionExample StringCapitalizer capitalize "hello"

Note, the different option config-merge-dir instructs the agent to extend theexisting configuration files instead of overwriting them. After re-building thenative image, the StringCapitalizer class and the capitalize method will beaccessible too.

Native Image - 图2

Generating Heap Dumps

GraalVM also supports monitoring and generating heap dumps of the Native Image processes.

Warning: This functionality is available in the Enterprise Edition of GraalVM.

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

Operational Information for Native Images

How can I specify the default amount of memory a native image can use when it gets executed?

  • To fine-tune maximum memory to be used by an image, set the percent value of physicalmemory using the -R:MaximumHeapSizePercent=<value> option. For moreinformation, unfold the native-image —expert-options-all list and search for-R:MaximumHeapSizePercent=<value>,-R:MaximumYoungGenerationSizePercent=<value>,-H:AllocationBeforePhysicalMemorySize=<value> and other related options.

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

  • When startup time, memory footprint and packaging size are 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 (GNU Project Debugger) and profilers (VTune).