Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Inside the JVM

    Bytecode and the JIT

    Bytecode is the instruction set javac produces. It's stack-based: instructions push values onto an operand stack and pop them off.

    Chapter 4 of 106 min read

    The Plain Picture#

    An actor first reads a new script line by line (slow). After performing the same scene a hundred times, they know it by heart and perform it fluently — even improving it, cutting pauses the script didn't need. If the director changes the scene, they go back to reading the script.

    The Real Names#

    • Bytecode is the instruction set javac produces. It's stack-based: instructions push values onto an operand stack and pop them off.

    • javap -c (a JDK tool) shows it. Here is score from the StudyBuddy report (Java Basics Ch 9):

    Java
    static int score(int correct, boolean onTime) {
        int points = correct * POINTS; // POINTS = 10
        if (onTime) points += 20;
        return points;
    }
    Output
    $ javap -c -p Score.class
      static int score(int, boolean);
        Code:
           0: iload_0              // push local variable 0 (correct)
           1: bipush        10     // push the constant 10  (POINTS was inlined by javac: it's a compile-time constant)
           3: imul                 // pop two, multiply, push the result
           4: istore_2             // pop into local variable 2 (points)
           5: iload_1              // push onTime
           6: ifeq          12     // if it's 0 (false), jump to instruction 12
           9: iinc          2, 20  // points += 20
          12: iload_2              // push points
          13: ireturn              // return it
    • The interpreter executes bytecode instruction by instruction — like reading the script line by line.

    • The JIT compiler (Just-In-Time — How Computers Work Ch 8) watches which methods and loops are hot (run often) and compiles them into optimised machine code stored in the code cache. HotSpot has two JIT compilers used together (tiered compilation):

      • C1 — compiles quickly with light optimisation, and adds profiling (which branches are taken, which types appear);

      • C2 — for the hottest code, uses that profile to optimise aggressively.

    Under the Hood — what the JIT does#

    1. Inlining — replaces a call to a small method with the method's body, removing call overhead and enabling everything else. (This is why getters cost nothing.)

    2. Speculation from the profile — "this call site has only ever seen MultipleChoice objects" → call its method directly, skipping the vtable (Object-Oriented Programming Ch 4). If a different type ever shows up, the JVM deoptimises: throws away the compiled code and falls back to the interpreter, then recompiles.

    3. Loop optimisations — unrolling, removing repeated bounds checks, hoisting unchanging reads out of loops (exactly what made the plain-flag loop in Concurrency Ch 4 run forever).

    4. Escape analysis — if an object never "escapes" the method (isn't stored in a field, returned, or passed somewhere that keeps it), the JIT can skip allocating it on the heap entirely and keep its fields in registers (scalar replacement).

    Escape analysis, measured — a loop creating 50 million tiny short-lived record objects:

    Output
    with escape analysis (default):     50M short-lived objects:  31 ms     young GCs: 0
    with -XX:-DoEscapeAnalysis:         50M short-lived objects:  99 ms     young GCs: 13

    With escape analysis the objects were never allocated at all — zero garbage collections. Turned off, the same code allocated 50 million objects and triggered 13 collections. (This also explains why a boxed-number benchmark can look surprisingly fast: the JIT may remove the boxes.)

    Warm-up (Part 0's problem 3): right after start-up, code is interpreted and profiles are empty, so the first requests are slow. Mitigations: send warm-up traffic before taking real traffic, keep enough instances so new ones ramp gently, CDS (class data sharing — pre-processed class data to start faster), or ahead-of-time compilation with GraalVM Native Image (very fast start-up; loses some peak optimisation and dynamic features).

    Check yourself

    5 questions
    1

    What does iload_0 / imul / ireturn tell you about how bytecode works?

    Show answer

    Bytecode is stack-based: instructions push values onto and pop them from an operand stack.

    2

    C1 vs C2?

    Show answer

    C1 compiles quickly with basic optimisations and collects profiling data; C2 compiles hot code with aggressive, profile-guided optimisations.

    3

    What is deoptimisation, and when does it happen?

    Show answer

    Discarding compiled code whose speculative assumptions (e.g. only one type seen) turned out false, falling back to interpretation and recompiling.

    4

    What did escape analysis do in the measured example?

    Show answer

    It proved the objects never escaped the method, so it eliminated their allocation — no heap objects, no GCs, about 3× faster.

    5

    Why is a Java service slow right after start-up?

    Show answer

    The code starts interpreted and the JIT hasn't compiled and optimised the hot paths yet (warm-up).