Execution engine practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most JIT questions, in interviews and in real projects, come down to three skills: reading what the JVM says it compiled, telling cold timings from warm ones, and spotting a timing test that measures the wrong thing. Each section below practises one of them on real output.
Watching methods become hot
-XX:+PrintCompilation prints a line for each compile.
Example 1 · A hostel fee bill: one hot method, one cold one
public class HostelFeeDemo { // Fee charge for one student for one day: Rs 120, Rs 150 on Sundays (feast) static int dailyCharge(int day) { return (day % 7 == 0) ? 150 : 120; }
// Called once: prints the month's summary static void monthlyReport(long total, int students) { System.out.println("Students: " + students); System.out.println("Fee total for 30 days: Rs " + total); }
public static void main(String[] args) { int students = 1_000; long total = 0; for (int s = 0; s < students; s++) { for (int day = 1; day <= 30; day++) { total += dailyCharge(day); } } monthlyReport(total, students); }}Students: 1000 Fee total for 30 days: Rs 3720000
What this code does
dailyChargeis called 30,000 times (1,000 students × 30 days), so it becomes hot. Every seventh day is a Sunday feast at Rs 150, the rest Rs 120.monthlyReportis called once. The next example shows which of the two the JIT compiled.
Example 2 · Reading the compilation log
java -XX:+PrintCompilation HostelFeeDemo | grep -E "HostelFee|Students|Fee total"139 73 3 HostelFeeDemo::dailyCharge (16 bytes) 139 74 4 HostelFeeDemo::dailyCharge (16 bytes) 139 73 3 HostelFeeDemo::dailyCharge (16 bytes) made not entrant Students: 1000 Fee total for 30 days: Rs 3720000
What this code does
dailyChargewent to level 3 (#73) and then level 4 (#74), and #73 was retired: a normal tier-up, all within about 1 ms. Your times and ids will differ.monthlyReportandmaindo not appear.mainruns about 31,000 loop rounds in total, below the back-edge level that triggers OSR, andmonthlyReportruns once.
To read a run, filter the lines for your own classes, then ask three questions for each method: which levels did it reach, was any compile an OSR compile (%), and was any level 4 version made not entrant?
A method called thousands of times, like dailyCharge below, normally shows level 3, then level 4, then the level 3 version retired. A method called once and without a loop, like monthlyReport, never appears at all, and that is fine: compiling it would gain nothing. A level 4 version that is retired, followed by a new compile id for the same method, is a deoptimization. One or two are normal; many for the same method are worth a look.
Comparing first-run and warmed-up timings
The first runs of any code measure the interpreter, class loading and compiling, not the steady speed.
Example 3 · Cold, warming and warm runs
public class CgpaTiming { // CGPA on a 10-point scale from 8 semester SGPAs stored as tenths (85 = 8.5) static int cgpaTenths(int[] sgpa) { int sum = 0; for (int s : sgpa) sum += s; return sum / sgpa.length; }
static long batch(int[][] students) { long total = 0; for (int[] s : students) total += cgpaTenths(s); return total; }
public static void main(String[] args) { int[][] students = new int[10_000][8]; for (int i = 0; i < students.length; i++) { for (int sem = 0; sem < 8; sem++) { students[i][sem] = 50 + (i + sem * 7) % 50; // 5.0 to 9.9 } } long checksum = 0; for (int run = 1; run <= 200; run++) { long start = System.nanoTime(); checksum += batch(students); long micros = (System.nanoTime() - start) / 1_000; if (run == 1 || run == 2 || run == 10 || run == 50 || run == 200) { System.out.println("Run " + run + ": " + micros + " us"); } } System.out.println("Checksum: " + checksum); }}Run 1: 1204 us Run 2: 492 us Run 10: 521 us Run 50: 55 us Run 200: 65 us Checksum: 148280000
What this code does
- Run 1 is cold (about 1.2 ms). Runs 2 and 10 are warming, about 0.5 ms, while C1 code runs and C2 is still compiling. By run 50 the time settles near 55 to 65 µs, about 20 times faster than run 1.
- The checksum is the same in every run of the program, which proves each run did the full work.
Example 4 · The same program with -Xint
java -Xint CgpaTimingRun 1: 3089 us Run 2: 2300 us Run 10: 2278 us Run 50: 2806 us Run 200: 2108 us Checksum: 148280000
What this code does
- Without the JIT, every run stays between about 2 and 3 ms. There is no warm-up curve, because nothing ever gets compiled.
- The normal run's cold run 1 (1.2 ms) is already faster than these, because C1 starts compiling during the first run. The warm runs are about 35 to 50 times faster than
-Xint.
So when you compare timings, always say which run you mean: cold (the first call), warming (while C1 and C2 are compiling) or warm (after the times have settled).
A quick way to see how much of a speed-up is the JIT is to run the same program with -Xint. If the cold run looks like the -Xint runs, and the warm runs are much faster, the difference is JIT compilation. Warm times still vary a little from run to run, so look at several warm runs or their median, never one.
Finding the flaw in a micro-benchmark
A micro-benchmark is a timing test for a small piece of code, such as one method. Most broken micro-benchmarks fail in a few common ways, listed after the two examples.
Example 5 · A broken benchmark: same work, different times
public class BrokenBenchmarkDemo { // Total attendance percentage points for a class (fixed pattern, 50 to 99) static int attendanceTotal(int students) { int total = 0; for (int i = 0; i < students; i++) { total += 50 + (i * 7) % 50; } return total; }
// Version A: loop that adds the same number again and again static int versionA(int students) { return attendanceTotal(students); }
static int versionB(int students) { return attendanceTotal(students); }
public static void main(String[] args) { // Flaw 1: no warm-up. Flaw 2: one run each. Flaw 3: results ignored. long t0 = System.nanoTime(); versionA(100_000); long t1 = System.nanoTime(); versionB(100_000); long t2 = System.nanoTime();
System.out.println("Version A: " + (t1 - t0) / 1_000 + " us"); System.out.println("Version B: " + (t2 - t1) / 1_000 + " us"); }}Version A: 2079 us Version B: 432 us
What this code does
versionAandversionBdo exactly the same work, yet A looks almost five times slower. A ran first, so it paid for interpreting and compilingattendanceTotal; B reused that compiled code.- In other runs B was the slow one, or A took 5 ms: one cold run each, with results thrown away, can say almost anything.
Example 6 · The fixed benchmark
import java.util.Arrays;
public class FixedBenchmarkDemo { static int attendanceTotal(int students) { int total = 0; for (int i = 0; i < students; i++) { total += 50 + (i * 7) % 50; } return total; }
static int versionA(int students) { return attendanceTotal(students); }
static int versionB(int students) { return attendanceTotal(students); }
static long checksum = 0; // fix 3: every result is used
static long medianMicros(boolean useA) { for (int i = 0; i < 3_000; i++) { // fix 1: warm-up, not measured checksum += useA ? versionA(10_000) : versionB(10_000); } long[] runs = new long[31]; // fix 2: many measured runs for (int r = 0; r < runs.length; r++) { long start = System.nanoTime(); for (int k = 0; k < 100; k++) { checksum += useA ? versionA(10_000) : versionB(10_000); } runs[r] = System.nanoTime() - start; } Arrays.sort(runs); return runs[runs.length / 2] / 1_000; }
public static void main(String[] args) { System.out.println("Version A median: " + medianMicros(true) + " us per 100 calls"); System.out.println("Version B median: " + medianMicros(false) + " us per 100 calls"); System.out.println("Checksum: " + checksum); }}Version A median: 1526 us per 100 calls Version B median: 1596 us per 100 calls Checksum: 9089000000
What this code does
- With warm-up, 31 measured runs, the median and a printed checksum, both versions come out within about 5 percent of each other, which is the honest answer for identical code.
- Occasionally one run on a busy laptop still shows a big gap. That is why JMH repeats the measurement in several fresh JVMs (forks); for decisions that matter, use it.
- No warm-up: the first version measured also pays for warming up shared code, so it looks slower.
- One run each: noise, a GC pause or a background compile decides the result.
- Results thrown away: the JIT may delete the work, so the time shows almost nothing.
- Extra work inside the timed part, such as
System.out.println, which can cost far more than the code being measured.
Interview questions on interpreter, JIT and warm-up
Interviewers usually start with a basic question and then follow up. Short, accurate answers built from the ideas of this module work best:
- "Is Java interpreted or compiled?" → both:
javacmakes bytecode, HotSpot interprets cold code and JIT-compiles hot code (C1, then C2). - "Why is a Java service slow just after a restart?" → JIT warm-up; hot paths are compiled only after they have run for a while.
- "What can make compiled code be thrown away?" → a broken speculation (a never-seen branch or type, a new subclass), which causes deoptimization.
- "How do you benchmark Java code?" → JMH, or at least warm-up, many runs, the median and used results.
Finish up
Mark complete & continue
Next: The JVM memory map