What does the JIT compiler do in the JVM, and when does it run?
The just in time compiler turns the bytecode of the methods that matter into machine instructions for the processor that is running the program.
The virtual machine starts by interpreting the bytecode, which means it runs the instructions one at a time. That gets the program started straight away, and it is quick to start but slow to run.
While the program runs, the virtual machine counts how often each method is called. When a method has been called often enough, and the method is worth the effort, the compiler takes it and produces a version that runs at full speed. After that, the method is never interpreted again.
public class Main {
public static void main(String[] args) {
// The first calls are interpreted, and then the JIT takes over.
long start = System.nanoTime();
long total = 0;
for (int index = 0; index < 20000000; index++) {
total = total + work(index);
}
long first = System.nanoTime() - start;
// By now the method has been compiled.
start = System.nanoTime();
total = 0;
for (int index = 0; index < 20000000; index++) {
total = total + work(index);
}
long second = System.nanoTime() - start;
System.out.println("the total : " + total);
System.out.println("the first run : " + (first / 1000000) + " ms");
System.out.println("the second run : " + (second / 1000000) + " ms");
}
static long work(int value) {
return value * 3L;
}
}
So when does it run? It depends on a threshold, and the threshold is not a fixed number of calls. The virtual machine also takes into account how long the method has been running for, how big it is, and what it does. A method that is in a loop that runs for ever will usually be compiled long before it has been called a thousand times.
The next question in this topic looks at the two stages of the compilation and at what happens when the compiled code turns out to be wrong.