Skip to content

Latest commit

 

History

History

java-kotlin-aot

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

Java and Kotlin Interoperability Demo

This repository contains the code for a demo application for GraalVM.

Prerequisites

Preparation

This is a simple Java/Kotlin application, where a Java method accesses a String from Kotlin and calls a Kotlin function, which later accesses a String from a Java class. This example demonstrates how easy it is to interop between Java and Kotlin.

  1. Download and install the latest GraalVM JDK using SDKMAN!.

    sdk install java 21.0.1-graal
  2. Download or clone the repository and navigate into the java-kotlin-aot directory:

    git clone https://github.com/graalvm/graalvm-demos
    cd graalvm-demos/java-kotlin-aot

Build the Application

To build the application use this command:

./build.sh

Look at this important line of the build.sh which creates a native executable for the Java application.

$JAVA_HOME/bin/native-image --no-fallback -cp ./target/mixed-code-hello-world-1.0-SNAPSHOT-jar-with-dependencies.jar -H:Class=hello.JavaHello -o helloworld --report-unsupported-elements-at-runtime

The native-image builder compiles the application ahead-of-time (AOT) for faster startup and lower general overhead at runtime. It takes a couple of parameters: the class path, the main class of the application with the -H:Class=... option, and the name of the resulting executable.

After executing the native-image command, check the directory, it should have produced an executable file helloworld.

Run the Application

To run the application, you need to execute the fat JAR file in the target directory. You can run it as a normal Java application using java. Or, since we have a native image prepared, you can run that directly.

The run.sh file executes it both ways and times them with the time utility.

time java -cp ./target/mixed-code-hello-world-1.0-SNAPSHOT-jar-with-dependencies.jar hello.JavaHello
time ./helloworld

The run.sh script produces approximately the following output:

./run.sh
+ java -cp ./target/mixed-code-hello-world-1.0-SNAPSHOT-jar-with-dependencies.jar hello.JavaHello
Hello from Kotlin!
Hello from Java!

real	0m0.646s
user	0m0.167s
sys	0m0.135s
+ ./helloworld
Hello from Kotlin!
Hello from Java!

real	0m0.030s
user	0m0.005s
sys	0m0.008s

The performance gain of the native version is largely due to the faster startup.

License

The sample application in this directory is taken from the JetBrains' Kotlin-examples repository.

The code from that repository is distributed under the Apache License 2.0. The code in this directory is also distributed under the Apache License 2.0. See LICENSE.md for more details.