Sub topic 2
What the JVM does while your code runs
This chapter assumes you can write and run Java programs from the command line, know what threads and a heap are, and can read a stack trace. It builds the working model that the rest of the tutorial relies on. Every profiler measurement reflects three things happening beneath your code: memory allocation, garbage collection, and just-in-time compilation.
Your code is not the only thing running
A Java program does not run as the machine code you might imagine from reading the source. The javac compiler turns source into bytecode. The JVM then runs that bytecode while doing other work in the background:
- Allocating objects on the heap, which is the memory area shared by all threads.
- Collecting garbage, which means finding objects nothing can reach any more and reclaiming their memory.
- Compiling hot code to machine code while the program is already running. The part that does this is the JIT (just-in-time) compiler.
These activities use CPU time and threads of their own. They can pause your code or make it faster. A profile that ignores them will mislead you. A method may look slow because it triggered a garbage collection, or fast only because the JIT has finished optimizing it.
The heap and generations
Objects created with new live on the heap. Thread stacks hold local variables and references, but not the objects those references point to. The HotSpot JVM (the default implementation in OpenJDK builds) divides the heap using the weak generational hypothesis: most objects die young.
| Area | Holds | Collected by |
|---|---|---|
| Young generation | Newly allocated objects | Frequent, short minor collections |
| Old generation | Objects that survived several minor collections | Rarer, more expensive collections |
| Metaspace | Class metadata, outside the heap proper | Class unloading |
Allocation in the young generation is cheap. In the common case it is a pointer bump inside a thread-local buffer. The cost appears later, when the young generation fills and a collection runs. Young collections copy the surviving objects and discard the rest, so their cost depends on how much survives, not on how much was allocated.
Two consequences matter for profiling:
- High allocation rate means frequent collections. Short-lived garbage is cheap per object, but a very high rate still burns CPU and can push objects into the old generation early.
- Objects that stay reachable cannot be collected. A leak in Java is an object you still reference without needing it. The old generation grows until a full collection cannot free enough, and you get an
OutOfMemoryError.
Garbage collection and pauses
A collector must sometimes stop application threads so it can examine references safely. This is a stop-the-world pause. Modern collectors do most of their work concurrently, but all of them still pause for some steps.
Collectors trade throughput against pause time:
- Parallel GC maximizes throughput with longer pauses.
- G1 (the default on modern JDKs for most machines) aims for a target pause time by collecting the heap in regions.
- ZGC and Shenandoah keep pauses very short by doing nearly all work concurrently, at some cost in CPU and memory overhead.
The collector you run changes the numbers you see, so record which one is in use before comparing measurements from two environments. The next chapters show how to read collector behavior from logs.
The JIT compiler and tiered compilation
The JVM begins by interpreting bytecode, which is slow but starts immediately. It counts how often each method is called and how often loops repeat. When a method is hot enough, the JIT compiles it to machine code. HotSpot has two compilers and moves code between them in tiers:
- C1 compiles quickly with modest optimization and collects profile data.
- C2 uses that profile data to compile with aggressive optimizations. It inlines small methods, removes bounds checks it can prove unnecessary, and eliminates allocations for objects that never escape a method (escape analysis).
C2 optimizes on assumptions drawn from the profile, for example that a virtual call always hits one class. If an assumption later fails, the JVM deoptimizes: it throws away the compiled code and returns to the interpreter. This is normal, but repeated deoptimization shows up as unexplained slowness.
The practical effect is warmup. A freshly started JVM runs slower than the same JVM a minute later. Any timing taken in the first seconds measures the interpreter and the compiler's own work, not steady-state speed. Chapter-level detail on warmup comes later. For now, treat early measurements with suspicion.
Seeing it happen
The following program runs the same allocation-heavy work repeatedly and reports the time per round and the cumulative garbage collection counts. The sink field is volatile so the JIT cannot prove that the allocated arrays are unused and remove them.
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
public class RuntimeDemo {
static volatile byte[] sink;
static long work() {
long sum = 0;
for (int i = 0; i < 5_000_000; i++) {
byte[] chunk = new byte[64];
chunk[0] = (byte) i;
sink = chunk;
sum += chunk[0];
}
return sum;
}
public static void main(String[] args) {
for (int round = 1; round <= 8; round++) {
long start = System.nanoTime();
long result = work();
long ms = (System.nanoTime() - start) / 1_000_000;
long collections = 0;
long gcMillis = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
collections += gc.getCollectionCount();
gcMillis += gc.getCollectionTime();
}
System.out.println("round " + round + ": " + ms + " ms, result=" + result
+ ", total GCs=" + collections + ", total GC time=" + gcMillis + " ms");
}
}
}Compile it with javac RuntimeDemo.java, then run it with a small heap so collections are frequent:
java -Xmx128m -Xlog:gc RuntimeDemoExpect two patterns. The early rounds are usually slower than the later ones, because the work loop starts in the interpreter and gets compiled while running. The GC counter keeps rising every round, because each round allocates hundreds of megabytes of short-lived arrays. Exact numbers vary by machine and JDK, so compare the pattern, not the values.
You can also watch the JIT directly with -XX:+PrintCompilation, which prints a line each time a method is compiled.
java -XX:+PrintCompilation RuntimeDemoLook for RuntimeDemo::work in the output. Lines marked made not entrant indicate that compiled code was discarded, which is deoptimization or replacement by a better tier.
Common errors when reasoning about the JVM
- Timing the first run. The first call includes interpretation and compilation. Measure after warmup, or use a benchmark harness. Chapter on JMH covers this.
- Blaming a method for GC time. The method that happens to allocate when the young generation fills gets the pause. The cause is the allocation rate across the whole program.
- Assuming
System.gc()helps. It requests a full collection, which is usually the most expensive kind. Remove such calls unless you have a measured reason. - Raising
-Xmxto hide a leak. A larger heap delays the failure and makes each full collection and heap dump larger. - Comparing runs on different collectors or JDK versions. Defaults change between releases, so state the exact JVM flags with every measurement.
How this model guides the rest of the work
Each tool in the following chapters observes one part of this model. GC logs and jstat show the heap and collector. Flight Recorder shows allocation, compilation, and thread activity together. Thread dumps show what the application threads were doing at one moment. When a number surprises you, ask first which part of the model produced it: your code, the collector, or the compiler.
Exercise
You run a service for 30 seconds and find that its first requests take 400 ms while requests after the first minute take 40 ms, with no code change. Name two JVM mechanisms that can explain this and one measurement you would take to tell them apart.
Show answer
The JIT compiler (code starts in the interpreter and is compiled to faster machine code only after it proves hot) and the heap and collector (early heap growth or collections can add pauses). To tell them apart, run with -XX:+PrintCompilation to see when the hot methods get compiled, and with -Xlog:gc to see whether pauses line up with the slow requests. If slow requests end when the hot methods reach C2, warmup is the cause. If they line up with GC pauses, the collector is.
Exercise
A colleague says young-generation garbage is free because allocation is just a pointer bump. What part of that claim is right, and what does it leave out?
Show answer
Allocation itself is cheap, and a young collection costs about as much as the number of surviving objects, not the number of dead ones. What the claim leaves out is that a high allocation rate fills the young generation faster, so collections run more often. Each one adds a pause and CPU work, and objects that survive several collections get copied into the old generation. Measure the allocation rate and GC frequency instead of assuming it is free.