barroco
barroco

Reputation: 3108

Can I compile Java to native code?

Is there any way to compile from Java to standalone (or library) machine code without requiring a JVM?

Upvotes: 102

Views: 70327

Answers (5)

Rob Audenaerde
Rob Audenaerde

Reputation: 20019

Yes!

Oracle has been working on the GraalVm, which supports Native Images. Check here: https://www.graalvm.org/

Native Image The native image feature with the GraalVM SDK helps improve the startup time of Java applications and gives them a smaller footprint. Effectively, it's converting bytecode that runs on the JVM (on any platform) to native code for a specific OS/platform — which is where the performance comes from. It's using aggressive ahead-of-time (AOT) optimizations to achieve good performance.

See more:

The Micronaut platform uses GraalVM to make native microservices:

Simple example

 public class HelloWorld {
     public static void main(String[] args) {
         System.out.println("Hello, Native World!");
     }
 }

Compiling java:

 javac HelloWorld.java

Compiling to native:

 native-image HelloWorld

Running (only the executable is needed):

 ./HelloWorld 

Output

 Hello, Native World!

Upvotes: 44

BullyWiiPlaza
BullyWiiPlaza

Reputation: 19185

Another possibility would be RoboVM. However, it only seems to work on Linux, iOS and Mac OS X.

As of today, the project still seems somewhat alive contrary to some posts online claiming the project to be dead.

Upvotes: 0

Mark
Mark

Reputation: 29119

Excelsior JET is a commercial Java to native code compiler. However, it was discontinued in May 2019.

Upvotes: 19

Peter Lawrey
Peter Lawrey

Reputation: 533482

Yes, the JIT in the JVM does exactly that for you.

In fact it can produce faster code than compiling the code in advance as it can generate code optimised for the specific platform based on how the code is used at runtime.

The JVM is always involved even if a very high percentage is compiled to native code as you could load and run byte code dynamically.

Upvotes: 9

James Kingsbery
James Kingsbery

Reputation: 7486

There used to be a tool called GCJ that was part of GCC, but it's been removed. Now, all the links in the GCC site re-direct to their non-GCJ equivalents.

NB: the comments all refered to my original answer saying you can compile Java to native code with GCJ.

Upvotes: 42

Related Questions