Java
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.
Exercise 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.
Show example solution
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));
}
}
Test yourself
-
When does the JIT kick in?
- When a method is hot enough
- As soon as a class is loaded
- At compile time
- When the program shuts down
Show answer
When a method is hot enough — The JIT compiles hot methods; it kicks in when the call threshold is exceeded.
-
Match the JIT concepts
- JIT
- Turns hot code into machine code
- Code cache
- Holds compiled code
- Warmup
- Warm-up period
- Tiered
- Combines interpretation and compilation
-
Complete the code cache term
// JIT derlenmiş makine kodunu _code cache_ bölgesinde tutar
String cacheName = "____";
Show answer
// JIT derlenmiş makine kodunu _code cache_ bölgesinde tutar
String cacheName = "code cache";
Next lesson: Runtime data areas