CodeBlanks Logo Icon CodeBlanks

JIT compiler

Learn the JIT compiler and its optimizations.

The JIT compiler

The JIT (Just-In-Time) compiler turns frequently run bytecode into machine code. The JVM first runs bytecode by interpreting it; once a method is called often enough, the JIT compiles it and later calls are faster.

In Java 21, the main JIT is HotSpot C2. The JIT stores compiled machine code in a memory region called the code cache. This gives a large speedup over interpretation.

The JIT's 'hot' code detection is based on call count; methods that exceed a threshold are compiled. That is why the JVM needs a 'warmup' period.

Interpretation and compilation

The JVM runs in two modes: interpretation and compilation. Interpretation runs bytecode line by line; it starts fast but is slow. Compilation turns hot methods into machine code; the initial cost is high but later calls are fast.

The JVM combines both with tiered compilation: first interpretation for quick startup, then compilation for speed. This gives both low warmup time and high peak speed.

Practice Run a hot loop

Define a Main class. Add an int sum(int n) method that sums integers from 1 to n (using a for loop). In main, call sum(100) and print the result with System.out.println.

Starter code

Main.java
public class Main {
    // Define a method that sums from 1 to n

    public static void main(String[] args) {
        // Call the method with 100 and print
    }
}

Sample solution

Main.java
public class Main {
    int sum(int n) {
        int total = 0;
        for (int i = 1; i <= n; i++) {
            total += i;
        }
        return total;
    }
    public static void main(String[] args) {
        Main m = new Main();
        System.out.println(m.sum(100));
    }
}

Expected output

5050

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does the JIT kick in?

  • When a method is hot enough Correct answer
  • As soon as a class is loaded
  • At compile time
  • When the program shuts down

Explanation: The JIT compiles hot methods; it kicks in when the call threshold is exceeded.

2 Match the JIT concepts

Term Meaning
JIT Turns hot code into machine code
Code cache Holds compiled code
Warmup Warm-up period
Tiered Combines interpretation and compilation

3 Complete the code cache term

Question
// JIT derlenmiş makine kodunu _code cache_ bölgesinde tutar
String cacheName = "____";
Answer
// JIT derlenmiş makine kodunu _code cache_ bölgesinde tutar
String cacheName = "code cache";

Explanation: Compiled code is kept in the code cache.

All lessons in Expert