87
votes

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

5
"compile" is the word you're looking for (rather than "compilate"). - T.J. Crowder
If your interest is speed, don't bother unless you're looking at a platform that HotSpot (Sun's JVM) doesn't support. HotSpot compiles bytecode to native code on the fly wherever a "hotspot" of execution path (something that gets run a lot) shows up, and it's very good at it. But if you're looking to avoid requiring a JVM, yes, look at the gcj James pointed you to. - T.J. Crowder
Yet another reason is protection against Java decompilers. As for HotSpot vs native compiler (vs JRockit vs IBM vs GCC vs Visual C++ vs hand-writing-CPU-instructions-in-hex) performance, it depends on the application, so YMMV. - Dmitry Leskov
I found one interesting development by Oracle for there Oracle database called JServer Accelerator. It was also designed to be platform Dependent in some way by compiling not to bytecodes but to C code. docs.oracle.com/cd/A87860_01/doc/java.817/a83727/jtools5.htm - supernova
I don't understand why this question was closed by the moderators. It seems perfectly clear to me. If they don't understand it then maybe the problem is with them. - isapir

5 Answers

41
votes

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.

31
votes

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:

19
votes

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

10
votes

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.

0
votes

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.