Lesson · JVM Internals
Bytecode: the frame model and the invocation family
16 min readBytecode
Locals, operand stack and the constant pool reference, then a real loop disassembled and executed instruction by instruction. Along the way: the five invocation instructions, and the silent rewrites javac performs for for-each, boxing, varargs, string concatenation and lambdas.
The code that is not in your source
Here is a loop that looks like a single operation. Predict what the machine actually does before you read on:
for (String name : names) { // names is a List<String> System.out.println(name); }
- Once:
names.iterator()is called through the interface, and the result is stored in a local variable you never declared. - Every iteration:
hasNext()andnext()are two more interface calls, so the loop body is bracketed by method calls you did not write. - A cast you never wrote: generics are erased, so
next()returns Object and javac inserts acheckcast java/lang/Stringto give it back its type.
The source is for you; the bytecode is for the machine. Every gap between them is a desugaring, and this lesson walks the ones you meet daily.
A frame is three things
Before the instruction list means anything, you need the furniture those instructions move values between. Every invocation pushes a frame, and every frame holds the same three pieces: an array of local variables, an operand stack, and a reference to the constant pool of the method's class.
The locals array is indexed storage, not scoped storage: a method with an int parameter, a long parameter and an int local uses slots 0, 1 to 2 and 3, because a long occupies two consecutive slots. In an instance method slot 0 holds this; in main slot 0 holds the args array.
| Piece | What it is | Declared where |
|---|---|---|
| Local variables | Numbered slots, one per variable; long and double take two consecutive slots | max_locals in the Code attribute |
| Operand stack | The scratch pad: instructions push and pop values here, and it is empty at statement boundaries | max_stack in the Code attribute |
| Constant pool reference | A pointer to the pool of the declaring class, so instructions can name fields, methods and literals | Implicit in every frame |
| Frame itself | One per active call, pushed on invocation and destroyed on return | Not in the file: it exists at runtime |
The operand stack is the scratch pad: arguments go up, results come down. max_stack and max_locals are computed by javac and checked by the verifier, never guessed at runtime.
One method, instruction by instruction
The method below sums an int array. It is five lines of Java, and the listing beside it is the whole machine truth: an initialisation, a guard, a body, an update, and a backward jump. There is no loop instruction in the JVM; a loop is a conditional jump plus a goto that points backwards.
Step through the player. Watch where iinc edits a local in place with no stack traffic at all, and where the loop condition has to rebuild its two operands from scratch on every pass.
A loop is a guard plus a backward jump. Once you can read that shape, every loop you profile stops being a black box.
sumOf(int[]) · locals and operand stack
listing · javap -c
sumOf(int[])locals
operand stack
empty
The frame for sumOf(new int[] { 4, 7 }): local 0 is a, local 1 is sum, local 2 is i. javac declared max_stack = 2 and max_locals = 3 for this method, and the operand stack starts empty.
Five ways to call a method
Method calls are where bytecode stops being arithmetic and starts being architecture. The JVM has exactly five invocation instructions, and the difference between them is not syntax: it is who decides which method body actually runs.
Four of them name their target through the constant pool. The fifth, invokedynamic, has no target in the instruction at all: a bootstrap method decides it, once, at first execution. The board below lays out the family.
| Instruction | Call site | Target resolved by | Typical client |
|---|---|---|---|
| invokestatic | static method | the class named in the pool | Math.abs, Integer.valueOf |
| invokespecial | constructor, private method, super call | fixed at compile time, no dispatch | new Foo(), super.toString() |
| invokevirtual | ordinary instance method | the receiver's runtime class | account.withdraw(x) |
| invokeinterface | interface method | the receiver's class, through its interface table | list.size(), it.next() |
| invokedynamic | anything the bootstrap decides | a bootstrap method, once per call site | lambdas, string concatenation since Java 9 |
invokevirtual is dispatch; invokedynamic is a decision made once at first call. The first looks up a method per call, the second links a target and reuses it.
Invocation family · five instructions
the difference is who decides which method body runsinvokestatic
target from the poolno receiver on the stack: only the arguments
invokespecial
target from the poolthe target is decided when javac emits the call
invokevirtual
target from the poolone lookup per call, through the class's method table
invokeinterface
target from the poolthe same idea, resolved against interfaces instead
invokedynamic
linked at first callThe instruction names no class and no method. A bootstrap method is called once, on first execution, and returns a CallSite; every later execution jumps straight to the linked target.
One call site per instruction occurrence, per class. Two lambdas in two places are two links; the same lambda evaluated twice reuses one.
its clients
The linked target is a method handle, so a JIT can inline it like any other call once it is hot.
for-each has two compilations
The opening loop has a cheaper sibling. Over an array, for-each needs no objects at all: javac compiles it to an index loop with arraylength as the bound, the same shape as the hand-written loop in the player above.
Over anything Iterable, the iterator protocol appears, and its cost is visible in the instruction list: one iterator() call before the loop, then hasNext() and next() on every pass, with the erased type restored by a cast.
// What javac actually runs for: for (String s : list) { body } for (Iterator<String> it = list.iterator(); it.hasNext(); ) { String s = it.next(); // returns Object after erasure, then checkcast String body; // your code, unchanged } // For an array there is no iterator at all: // iconst_0 / istore_i ; iload_i / aload_arr / arraylength / if_icmpge ; ... ; iinc i, 1 ; goto
- Array: an index local, a length check,
ialoadfor each element,iincfor the update. No iterator, no casts, no interface calls. - Iterable: call
iterator()once and store it in a hidden local. - Loop head: call
hasNext()and jump out when it returns false. - Loop body: call
next(), cast the erased result back to the element type, store it in the loop variable, then run your code. - Loop tail: jump back to the head. Three interface calls per element, which is why hot index loops sometimes get rewritten by hand.
Arrays compile to indexes; collections compile to iterators. Same syntax, roughly triple the work per element.
Boxing, varargs, concatenation, switches
The rest of the sugar lives at the same level: constructs that look like syntax and compile to calls, allocations or jump tables. Four of them show up in almost every profiling session.
- Boxing:
list.add(5)compiles toinvokestatic Integer.valueOf(I), and later a standaloneint x = boxed;compiles toinvokevirtual Integer.intValue(). Values from -128 to 127 come from a cache, so small boxes may be shared while large ones allocate on every call. - Varargs: the call site builds the array.
log("a", "b")compiles to an array allocation followed by the call; a call with no values still allocates an empty array. - String concatenation: Java 8 and earlier built a
StringBuilderchain. Since Java 9 the compiler emitsinvokedynamicwhose bootstrap isStringConcatFactory.makeConcatWithConstants, and the recipe describing the shape of the concatenation is baked into the call site. A loop that concatenates still allocates per iteration, whichever mechanism is used. - Switches: an int switch becomes
tableswitch(dense values, one jump table) orlookupswitch(sparse, a sorted list of key and target pairs). A String switch becomes alookupswitchonhashCode()followed by anequalscheck per candidate, and an enum switch uses a syntheticint[]that maps ordinals to case numbers.
Sugar is real code. Every silent rewrite is an instruction you can see in javap -c and a cost you can measure at runtime.
Lambdas ride invokedynamic
A lambda expression compiles to exactly one invokedynamic instruction. There is no generated class file per lambda, the way there is for an anonymous class: the body becomes a private synthetic method, and the call site is what turns it into an object implementing the functional interface.
The bootstrap method for a lambda is LambdaMetafactory.metafactory. It runs once per call site, on first execution, and hands back a CallSite; from then on every execution of that instruction uses the linked target. A lambda that captures nothing is linked to a single cached instance, while a capturing lambda allocates a fresh object each time it is evaluated.
A lambda is a call site, not a class. Linkage happens once, and what happens after that is a method handle call, which the JIT can inline like any other.
Reading it yourself
The gap between source and bytecode is readable, and the JDK already ships the reader. A short routine answers most questions that start with 'what does this actually do'.
javap -c MyClassdisassembles every method, instruction by instruction, with the constant pool references resolved as comments.javap -c -p MyClassadds private members, which is where the synthetic methods behind lambdas live.javap -v MyClassadds the Code attribute details and the constant pool itself: max_stack, max_locals, and every entry the instructions point at.- Read the listing against the frame model: pushes and pops tell you what is on the operand stack, and local slots tell you what survives across statements.
- When you need to generate or transform bytecode rather than read it, reach for ASM or Byte Buddy; since JDK 24 the JDK itself ships the Class-File API, which parses and writes class files as a first-class library.
javap -c is the first tool, not the last resort. If the JVM will run it, javap will show it, and the frame model is all the documentation most listings need.
The receiver is pushed too
Instance calls take their receiver from the operand stack like any other argument, and it is pushed before the arguments. That is why a null builder fails on the first call in builder.append(a).append(b), and why a listing shows one more value on the stack than the source appears to have arguments. Read the stack as the full argument list, receiver included, and null-related stack traces stop being surprises.
Interview angles
Why does the JVM use an operand stack instead of registers?+
A stack machine keeps instructions compact, since no register numbers have to be encoded, makes bytecode portable across architectures with different register files, and gives the verifier a simple shape to check: types flow through a stack of known depth.
Register machines such as Android's ART make the opposite trade: fewer instructions for the same work, but a format tied to a register model. HotSpot recovers the difference at runtime, because the JIT is free to map the operand stack onto physical registers once nothing observable depends on it.
Common misconception: That the JVM cannot use CPU registers. The hardware always uses registers; the bytecode format is what does not name them.
What are max_stack and max_locals, and who checks them?+
They are per-method values in the Code attribute: the deepest the operand stack ever gets and the number of local slots the method uses. javac computes both while emitting instructions, and the verifier then checks the code never exceeds them.
They are a frame budget that makes verification cheap: the verifier knows in advance how large the stack can grow, so it can track types through every instruction without solving for a variable depth. A hand-written class file with a wrong max_stack is rejected before it ever runs.
Follow-up: Why does a long parameter change max_locals?
How does a for-each over a List differ from one over an int[]?+
Arrays compile to an index loop with arraylength, iaload and iinc: no objects, no casts. A List compiles to the iterator protocol: iterator() once, then hasNext() and next() per element, with a checkcast because generics are erased.
That is why a hot loop over an ArrayList is sometimes rewritten as an index loop, and why removing an element inside a for-each is a routing problem for the iterator rather than a curiosity of the syntax.
for (int x : intArray) { } // index loop, no allocations for (String s : stringList) { } // iterator(), hasNext(), next() + checkcast
Common misconception: That for-each is a language primitive the VM understands. The VM only sees plain calls and jumps; the iterator shape is written by the compiler.
What happens the first time an invokedynamic instruction executes?+
The JVM calls its bootstrap method, which returns a CallSite describing the target. The call site is linked once, and every later execution invokes the linked target directly.
Lambdas use LambdaMetafactory as their bootstrap: it produces a method handle for the synthetic body method and wraps it into the functional interface. String concatenation since Java 9 uses StringConcatFactory, which reads a recipe compiled from the concatenation shape.
Common misconception: That invokedynamic re-resolves its target on every call. It is linked per call site; re-linking only happens if a bootstrap deliberately supports it, as switching implementations does.
Follow-up: Where does the lambda body live, if not in a generated class?
Where do long and double values go in the locals table?+
They occupy two consecutive slots, and the pair is always read and written as one value. Parameters are numbered by slot, so a long parameter shifts every later parameter by one extra slot.
The same rule applies to the operand stack in the sense that the JVM treats a long as a single stack value of double width, which verification tracks explicitly.
static void f(long a, int b) { // a: slots 0 and 1, b: slot 2 long c = a; // c: slots 3 and 4 }
Follow-up: What does that do to max_locals for a method with several long parameters?
How is string concatenation compiled, and what changed in Java 9?+
Before Java 9, javac emitted a StringBuilder chain: a constructor call, one append per piece, and toString. Since Java 9 it emits a single invokedynamic whose bootstrap, StringConcatFactory, builds the result from a recipe baked into the call site.
The indy form moves the decision of how to concatenate to runtime, so the JVM can pick buffers, reuse constants and apply optimizations it could not see in a fixed StringBuilder shape. Allocation behaviour is still per evaluation, which is why concatenation inside a loop still costs.
Common misconception: That the change eliminated intermediate objects. For dynamic values it did not; it made the mechanism optimizable rather than fixed.