The interpreter and the JIT compiler
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Java program starts quickly, yet after a few seconds the same code runs much faster. Bytecode alone cannot explain that. What inside the JVM is running your code, and how does it speed up?
The interpreter runs bytecode one instruction at a time
The JIT (just-in-time) compiler turns frequently run bytecode into fast native machine code while the program is running.
The interpreter reads one bytecode instruction, does what it says, and moves to the next one. It needs no preparation, so your program starts running as soon as its classes are loaded.
public class FeeCalc { static int totalFee(int tuition, int hostel) { int total = tuition + hostel; return total; }
public static void main(String[] args) { System.out.println(totalFee(85000, 40000)); }}125000
Bytecode is a list of small steps for a stack machine. iload_0 pushes the first int argument onto the operand stack (a small working stack each method call gets). iadd pops two values and pushes their sum. ireturn returns the top value. javap -c prints these steps (Example 1).
Example 1 · Seeing bytecode with javap -c
javac --release 17 FeeCalc.javajavap -c FeeCalcCompiled from "FeeCalc.java"
public class FeeCalc {
public FeeCalc();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
static int totalFee(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: istore_2
4: iload_2
5: ireturn
public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #13 // int 85000
5: ldc #14 // int 40000
7: invokestatic #15 // Method totalFee:(II)I
10: invokevirtual #21 // Method java/io/PrintStream.println:(I)V
13: return
}What this code does
totalFeebecomes six instructions: load both arguments, add them, store the sum in local variable 2, load it again and return it. The numbers on the left are byte positions inside the method.- This listing came from
javacof JDK 21 with--release 17. Anotherjavacmay number the constant pool entries (#7,#13) differently, but the instructions fortotalFeeare the same.
Example 2 · A toy interpreter for the same bytecode
import java.util.ArrayDeque;import java.util.Deque;
public class ToyInterpreterDemo { // A simplified model of an interpreter loop: fetch, decode, execute, repeat. // Real HotSpot has about 200 bytecodes and is written in machine code. static int run(String[] program, int[] locals) { Deque<Integer> stack = new ArrayDeque<>(); int pc = 0; while (true) { String[] parts = program[pc].split(" "); System.out.println("pc=" + pc + " " + program[pc] + " stack=" + stack); switch (parts[0]) { case "iload" -> stack.push(locals[Integer.parseInt(parts[1])]); case "istore" -> locals[Integer.parseInt(parts[1])] = stack.pop(); case "iadd" -> { int b = stack.pop(); int a = stack.pop(); stack.push(a + b); } case "ireturn" -> { return stack.pop(); } default -> throw new IllegalStateException("Unknown: " + parts[0]); } pc++; } }
public static void main(String[] args) { // The bytecode of totalFee(85000, 40000), as javap printed it String[] totalFee = {"iload 0", "iload 1", "iadd", "istore 2", "iload 2", "ireturn"}; int[] locals = {85000, 40000, 0}; int result = run(totalFee, locals); System.out.println("Result: " + result); }}pc=0 iload 0 stack=[] pc=1 iload 1 stack=[85000] pc=2 iadd stack=[40000, 85000] pc=3 istore 2 stack=[125000] pc=4 iload 2 stack=[] pc=5 ireturn stack=[125000] Result: 125000
What this code does
- The
whileloop is the heart of every interpreter: fetch the instruction atpc, decode it withswitch, execute it, then movepcon. The stack prints with its top value first. - Six instructions needed six trips round the loop, and each trip split a string and ran a
switch. That extra work around every instruction is exactly why interpreting is slower than running machine code.
The cost is speed. For every instruction the interpreter must fetch it, work out what it is and jump to the code that handles it. It pays this cost again every time the same line runs, even the millionth time.
The JIT compiler turns hot code into machine code
A just-in-time (JIT) compiler translates bytecode into machine code, the native instructions your CPU runs directly, while the program is running. "Just in time" means it compiles a method only after the program shows that it needs it.
Example 3 · Warm-up: the same work gets faster
public class WarmUpDemo { // Total marks of one student: the digits of the roll number act as marks static int digitTotal(int roll) { int total = 0; while (roll > 0) { total += roll % 10; roll /= 10; } return total; }
// One "round": process every roll number from 1 to 200,000 static long round() { long sum = 0; for (int roll = 1; roll <= 200_000; roll++) { sum += digitTotal(roll); } return sum; }
public static void main(String[] args) { for (int r = 1; r <= 8; r++) { long start = System.nanoTime(); long sum = round(); long micros = (System.nanoTime() - start) / 1_000; System.out.println("Round " + r + ": " + micros + " us (sum " + sum + ")"); } }}Round 1: 7533 us (sum 4600002) Round 2: 3577 us (sum 4600002) Round 3: 2437 us (sum 4600002) Round 4: 1636 us (sum 4600002) Round 5: 1256 us (sum 4600002) Round 6: 1308 us (sum 4600002) Round 7: 1203 us (sum 4600002) Round 8: 1187 us (sum 4600002)
What this code does
- Every round does exactly the same work, and the sum proves it. Round 1 still took about six times as long as round 8, because at first
digitTotalandroundwere interpreted. - During rounds 1 to 4 the JVM compiled the hot methods in the background. From then on each round ran machine code. Your numbers will differ by machine and run, but the falling pattern is typical.
The JVM counts how often each method is called and how often each loop goes round. Code that runs very often is called hot. Hot methods are sent to the JIT, which compiles them on separate background threads. Meanwhile your program keeps running in the interpreter. When the machine code is ready, the next call uses it. Compiled code has no fetch-and-decode step, keeps values in CPU registers and is optimised, so it is often many times faster than interpreting the same bytecode.
Mixed mode: why Java is both interpreted and compiled
Mixed mode means the interpreter and the JIT work together: cold code is interpreted, hot code is compiled. It is the default on HotSpot, and java -version says mixed mode in its last line.
Example 4 · Interpreter only versus mixed mode
java -Xint WarmUpDemojava WarmUpDemo$ java -Xint WarmUpDemo Round 1: 34806 us (sum 4600002) Round 2: 44505 us (sum 4600002) Round 3: 99793 us (sum 4600002) Round 4: 39200 us (sum 4600002) Round 5: 44293 us (sum 4600002) Round 6: 39270 us (sum 4600002) Round 7: 37120 us (sum 4600002) Round 8: 40398 us (sum 4600002) $ java WarmUpDemo Round 1: 7176 us (sum 4600002) Round 2: 3179 us (sum 4600002) Round 3: 1985 us (sum 4600002) Round 4: 1806 us (sum 4600002) Round 5: 1742 us (sum 4600002) Round 6: 1687 us (sum 4600002) Round 7: 1732 us (sum 4600002) Round 8: 1846 us (sum 4600002)
What this code does
- With
-Xintthe JIT is switched off. Every round stays slow (about 35 to 45 ms, with one slow outlier from other work on the machine) because nothing is ever compiled. - In normal mixed mode the same program settles at under 2 ms per round, more than 20 times faster. The exact ratio depends on your CPU and the code, so treat it as an example, not a rule.
So a Java program is compiled twice. javac compiles your source to bytecode ahead of time. At run time the JIT compiles the hot parts of that bytecode to machine code. Everything else is interpreted. Why not compile every method at startup? Most code runs only a few times, so compiling it would waste time before the program even begins. Waiting also helps: by the time a method is hot, the JVM has watched it run and knows which branches and types really occur, so it can optimise for them.
-Xint (interpreter only) is for experiments like Example 4. Never use it for a real application.The code cache: where compiled code lives
The code cache is an area of native memory, outside the Java heap, where the JVM keeps the machine code that the JIT produces. When a compiled method is called, the JVM jumps straight into its code there.
Example 5 · Looking inside the code cache
java -XX:+PrintCodeCache WarmUpDemoRound 1: 7557 us (sum 4600002)
...
Round 8: 2190 us (sum 4600002)
CodeHeap 'non-profiled nmethods': size=120000Kb used=73Kb max_used=73Kb free=119926Kb
bounds [0x00000224da240000, 0x00000224da4b0000, 0x00000224e1770000]
CodeHeap 'profiled nmethods': size=120000Kb used=219Kb max_used=219Kb free=119780Kb
bounds [0x00000224d2770000, 0x00000224d29e0000, 0x00000224d9ca0000]
CodeHeap 'non-nmethods': size=5760Kb used=1259Kb max_used=1272Kb free=4501Kb
bounds [0x00000224d9ca0000, 0x00000224d9f10000, 0x00000224da240000]
total_blobs=578 nmethods=198 adapters=285
compilation: enabled
stopped_count=0, restarted_count=0
full_count=0What this code does
-XX:+PrintCodeCacheprints the code cache when the JVM exits (the middle rounds are trimmed with ...). The threeCodeHeaplines are the three parts: about 117 MB each for the two nmethod parts and about 5.6 MB for non-nmethods, 240 MB in total.nmethods=198says 198 Java methods were compiled, most of them JDK methods used during startup.compilation: enabledconfirms the JIT was still working at the end; it would say otherwise if the cache had filled up.
On HotSpot (Java 9 and later) the code cache is split into three parts: non-nmethods for the JVM's own helper code (such as the interpreter), profiled nmethods for quick first versions of methods, and non-profiled nmethods for the fully optimised versions. An nmethod is HotSpot's name for one compiled Java method. The code cache has a fixed maximum size, set by -XX:ReservedCodeCacheSize. On HotSpot for Java 17 and 21 it is 240 MB by default when tiered compilation is on (the normal setting). If it ever fills up, the JVM prints a warning and stops compiling new code; the program keeps running, but new hot code stays interpreted and slow.
HotSpot: the JVM in standard JDK builds
HotSpot is the JVM inside OpenJDK, so it is the JVM in almost every standard JDK build: Oracle JDK, Eclipse Temurin, Amazon Corretto, Microsoft Build of OpenJDK and others.
Example 6 · Which JVM am I running?
java -versionjava -Xint -version$ java -version openjdk version "21.0.7" 2025-04-15 OpenJDK Runtime Environment ... (build 21.0.7+9-...) OpenJDK 64-Bit Server VM ... (build 21.0.7+9-..., mixed mode, sharing) $ java -Xint -version openjdk version "21.0.7" 2025-04-15 OpenJDK Runtime Environment ... (build 21.0.7+9-...) OpenJDK 64-Bit Server VM ... (build 21.0.7+9-..., interpreted mode, sharing)
What this code does
- The vendor name and build number (trimmed with ... here) differ between Temurin, Corretto, Oracle JDK and others.
64-Bit Server VMtells you it is HotSpot. - The words in brackets show the execution mode:
mixed modeby default,interpreted modewith-Xint.sharingmeans class data sharing is in use.
Its name comes from its main idea: find the hot spots of a program and compile those. HotSpot has two JIT compilers, called C1 and C2, which the next lesson covers. Other JVMs exist, such as Eclipse OpenJ9, and they make different choices. Everything in this module describes HotSpot on Java 17 and 21.
Server VMinjava -versionoutput means the HotSpot server build, the normal one on 64-bit machines.mixed modemeans interpreter plus JIT;interpreted modeappears only with-Xint.sharingmeans class data sharing is on, a startup feature covered later in this module.
Next step
Check your understanding
11 quick questions