iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🖥

Reading the JVM | JVM Structure Part 7 - Object Creation and Control Flow

に公開
2025/09/21

Continuation from the previous article. Please find the previous article here:

https://zenn.dev/peyang/articles/reading-jvm-chapter-02-11-1-4

This series is structured as a guide for reading the JVM specification.
Since the JVM specification is extremely lengthy and complex, we summarize the key points for each section.
Additionally, by understanding the internal structure and operational principles of the JVM, we aim to deeply comprehend Java's performance, security, and memory management mechanisms.

The series index is here:

https://zenn.dev/peyang/articles/reading-jvm-chapter-00

Chapter 2: The Structure of the Java Virtual Machine

Chapter 2 of the JVM specification is titled "The Structure of the Java Virtual Machine."
However, this chapter is particularly long and complex even among the seven chapters of the JVM specification, so we will explain it in eight parts.

This part covers the contents of Chapter 2.11.5 through Chapter 2.11.10.

2.11.5 Object Creation and Manipulation (› 2.11.5 Object Creation and Manipulation)

Both class instances and arrays are treated as objects (structured data), but their creation and manipulation use different instructions.

Object Creation

Object creation is performed using new-family instructions.

  • new: Creates a class instance (equivalent to new Object()).
  • newarray: Creates an array of primitive types (e.g., int[], byte[]).
  • anewarray: Creates an array of reference types (e.g., String[]).
  • multianewarray: Creates a multidimensional array (e.g., int[][], String[][]).

Object Access

Access to instance fields and static fields of objects is performed using get-family and put-family instructions.

  • getfield: Retrieves an instance field.
  • putfield: Sets a value in an instance field.
  • getstatic: Retrieves a static field.
  • putstatic: Sets a value in a static field.

Array Access

Access to array elements is performed using aload-family and astore-family instructions.
The former retrieves an element from an array, and the latter sets a value in an array element.

Furthermore, these instructions are named with a specific prefix depending on the element type.
(For byte arrays: baload and bastore; for char arrays: caload and castore; and so on.)

Example:

aload 0     // Push the array onto the stack
iconst_0    // Push the index of the element to retrieve onto the stack
baload      // Retrieve the element from the array at the top of the stack and push it onto the stack

Getting the Length of an Array

To get the length of an array, use the arraylength instruction.
This instruction pushes the length of the array onto the stack.
Note that this instruction is orthogonal; it does not depend on the element type of the array.

aload 0     // Push the array onto the stack
arraylength // Get the length of the array at the top of the stack and push it onto the stack

2.11.6 Operand Stack Management Instructions (› 2.11.6 Operand Stack Management Instructions)

The operand stack is a stack used for temporarily storing values that JVM instructions operate on.
The following orthogonal instructions are used to manage the operand stack:

  • dup: Duplicates the top value on the stack.
    ..., value -> ..., value, value
    
  • dup_x1: Duplicates the top value and places the duplicate one position down.
    ..., value1, value2 -> ..., value2, value1, value2
    
  • dup_x2: Duplicates the top value and places the duplicate two positions down.
    ..., value1, value2, value3 -> ..., value2, value3, value1, value2
    
  • dup2: Duplicates the top two values on the stack.
    ..., value1, value2 -> ..., value1, value2, value1, value2
    
  • dup2_x1: Duplicates the top two values and places the duplicates three and four positions down.
    ..., value1, value2, value3 -> ..., value2, value3, value1, value2
    
  • dup2_x2: Duplicates the top two values and places the duplicates four and five positions down.
    ..., value1, value2, value3, value4 -> ..., value2, value3, value4, value1, value2
    
  • pop: Removes the top value from the stack.
    ..., value1, value2 -> ..., value1
    
  • pop2: Removes the top two values from the stack.
    ..., value1, value2, value3 -> ..., value1
    
  • swap: Swaps the top two values on the stack.
    ..., value1, value2 -> ..., value2, value1
    

2.11.7 Control Transfer Instructions (› 2.11.7 Control Transfer Instructions)

Control transfer instructions change the execution flow of a program (conditionally or unconditionally).
These instructions transfer control to a specified instruction without executing the subsequent instructions.

Such instructions include:

  • goto: Unconditionally jumps to a specified label.
  • if-family instructions: Conditionally jump to a specified label.
  • tableswitch, lookupswitch: Jump to a specified label based on an integer value.
  • jsr: Jump to a subroutine.
  • ret: Return from a subroutine.

Conditional Branches

The JVM provides a rich set of instructions for comparing data of int type or reference types and then jumping conditionally.
There are also instructions for jumping when a null reference is encountered.

For numeric comparisons, different instructions are used depending on the type.
To compare values of type boolean, byte, char, short, or int, use int-typed conditional branch instructions.

Example:

instructions:
  iconst_0  // Push 0 onto the stack
  iconst_0  // Push 0 onto the stack
  if_icmpeq label // Jump to label if the top two values are equal
  // Processing when the condition is not met …

label:
  // Processing when the condition is met …

On the other hand, to compare values of type long, float, or double, first use dedicated instructions to compare the data (which returns an int result), and then use int-typed conditional branch instructions.
After the comparison instruction, you use an int-typed conditional branch instruction to test the comparison result and jump accordingly.
Because of this usage, the JVM provides a rich set of conditional branch instructions for the int type.

Example:

instructions:
  lconst_0  // Push long 0 onto the stack
  lconst_0  // Push long 0 onto the stack
  
  // Compare the two long values on top of the stack and push the result as an int.
  // The result is 0 (equal), 1 (left greater), or -1 (right greater).
  lcmp       
  iconst_0  // Push 0 onto the stack
  
  // Jump to label if the top two values are equal.
  // Here, since we are comparing with 0, it jumps when the two long values are equal.
  if_icmpeq label 
  // Processing when the condition is not met …
  
label:
  // Processing when the condition is met …

2.11.8 Method Invocation and Return Instructions (› 2.11.8 Method Invocation and Return Instructions)

Method invocation and return are among the important functions of the JVM.
Method invocation is performed using invoke-family instructions, and returning from a method uses return-family instructions.

Method Invocation

Method invocation uses different instructions depending on the type of method being called.

Specifically, the following instructions exist:

  • invokestatic: Invokes a static method.
  • invokevirtual: Invokes an instance method.
  • invokespecial: Invokes special methods (such as constructors and superclass methods).
  • invokeinterface: Invokes an interface method.
  • invokedynamic: Dynamically resolves and invokes a method.

The invokedynamic instruction was introduced in Java 7 and supports dynamic method invocation.
A major characteristic and complex aspect of this instruction is that the concrete method to be called is determined at runtime (more precisely, at link time).
This dynamic resolution is performed by calling a special method called the bootstrap method when the invokedynamic instruction is invoked.
The bootstrap method is specified as an operand of invokedynamic, along with the name and signature of the method to be called.

The bootstrap method is usually a static method with the ACC_STATIC flag, and has a signature like the following:

static CallSite bootstrap(
    MethodHandles.Lookup caller,
    String name,
    MethodType type,
    Object... args
);

Note that arguments to the method can be freely specified, but it must always have a MethodHandles.Lookup argument as the first parameter.
This method is called only once during the linking of invokedynamic, and returns a CallSite containing an appropriate method handle.
The linked CallSite is cached for that class, method, and instruction, and is used directly for subsequent calls to the same instruction.

Peyang's Note

The invokedynamic instruction is used to implement features of the Java language such as lambda expressions and method references.
For example, consider the following lambda expression:

Function<Integer, Integer> square = x -> x * x;

This lambda expression is resolved at runtime using the invokedynamic instruction.
Specifically, when the invokedynamic instruction is invoked, the bootstrap method metafactory of the class java/lang/invoke/LambdaMetafactory is called.
The JVM calls this method in the following flow to resolve the runtime type of the lambda expression and return an appropriate method handle:

  1. The execution reaches the invokedynamic instruction.
  2. On the first invocation, the JVM executes LambdaMetafactory.metafactory.
  3. This returns a CallSite, and a MethodHandle to the body of the lambda expression is registered there.
  4. For subsequent invocations, that handle is used directly for fast invocation.

Thus, the invokedynamic instruction functions as a flexible and high-performance foundation for achieving both static typing and dynamic behavior in the Java language.
It is the only instruction that possesses the dynamic behavior that traditional JVM invocation instructions lacked, making it indispensable for the evolution of Java.

Method Return

Return instructions are distinguished by the return type as follows:

  • ireturn: Returns a value of type int (including boolean, byte, char, short).
  • lreturn: Returns a value of type long.
  • freturn: Returns a value of type float.
  • dreturn: Returns a value of type double.
  • areturn: Returns a value of a reference type.
  • return: Returns from a method with no return value (void).

2.11.9 Throwing Exceptions (› 2.11.9 Throwing Exceptions)

Throwing an exception is performed using the athrow instruction.
This instruction throws the exception object at the top of the stack.
Additionally, when the JVM encounters an abnormal condition during the execution of various instructions, it throws an exception.

These exceptions interrupt the normal control flow of the program and transition to a special flow for exception handling.

2.11.10 Synchronization (› 2.11.10 Synchronization)

The JVM directly supports synchronization control between threads, providing functionality to prevent race conditions when multiple threads access the same object.
This uses the JVM's monitor mechanism.
Monitors provide exclusive control over methods or sequences of instructions within methods.

Every object has a monitor, and each monitor tracks the thread that owns it and an entry count.
The owning thread is the thread that has acquired the monitor.
The entry count represents the number of times that thread has acquired the monitor.

To acquire a monitor, a thread must obtain ownership of that monitor and increment the entry count.
To release a monitor, the entry count is decremented; when the entry count reaches zero, ownership is released.

While a thread holds a monitor, no other thread can acquire that monitor.
If another thread attempts to acquire the monitor, its execution is blocked (enters the WAITING state) until the monitor is released.

Method-Level Synchronization

If a method has the ACC_SYNCHRONIZED flag (the synchronized flag), that method is a synchronized method.

No special processing written in the program is required for calling a synchronized method.
Therefore, the JVM automatically acquires and releases the monitor when a program calls a synchronized method.

To invoke a synchronized method, the monitor of the object to which the method belongs must be acquired.
When the execution of the synchronized method completes (whether normally or abnormally), the monitor is automatically released.

As mentioned, while one thread holds a monitor, other threads cannot acquire it.
Therefore, if multiple threads try to call a synchronized method on the same object simultaneously, only the thread that first acquires the monitor can execute the method; other threads are blocked until the monitor is released.

Instruction Sequence Synchronization

Synchronization of instruction sequences is implemented via the synchronized block in Java.

The JVM implements the monitorenter and monitorexit instructions to provide this synchronization. These are important instructions for realizing structured locking.

Structured locking is a concept that assumes the acquisition and release of a monitor occur in pairs according to a static code structure.
That is, it is expected that a monitor acquired in a block is always released at the end of that block (or upon exit via an exception).

However, there is no guarantee that all code executed by the JVM correctly follows structured locking.
For example, tools that directly generate bytecode or low-level code that directly manipulates the JVM instruction set may unintentionally violate structured locking.

Therefore, the JVM may enforce the following two rules to ensure structured locking:

  1. The number of times a thread acquires a certain monitor must equal the number of times that thread releases that monitor.
    → Guarantees that acquisitions and releases are paired.
  2. At any point in a method invocation, the number of releases of a monitor by a thread must not exceed the number of acquisitions of that monitor.
    → Guarantees that releases do not exceed acquisitions.

Summary

This article explained a part of Chapter 2 of the JVM specification.
We detailed the structure of the JVM, object creation and manipulation, control transfer instructions, method invocation and return instructions, throwing exceptions, and synchronization.
In particular, for control transfer instructions, we explained conditional branching and method invocation/return instructions in detail.
We noted that dedicated instructions are available for certain types for integer conditional branching, and also touched on the dynamic method invocation of the invokedynamic instruction.
Additionally, we explained the mechanisms of throwing exceptions and synchronization.

This knowledge is important for understanding the internal structure and operating principles of the JVM.

Next time, as an interlude, we will explain the requirements and principles that the JVM must satisfy (Chapters 2.12 and 2.13).
Then, have a great bytecode life!

Next Article Link

https://zenn.dev/peyang/articles/reading-jvm-chapter-02-12-13

  • Lindholm, T., Yellin, F., Bracha, G., & Smith, W. M. D. (2025). The Java® Virtual Machine Specification: Java SE 24 Edition.
  • Lindholm, T., & Yellin, F. (1999). The Java™ Virtual Machine Specification (2nd ed.). Addison-Wesley. ISBN 978-0-201-43294-7
  • Otavio, S. (2024). Mastering the Java Virtual Machine. Packet Publishing. ISBN 978-1-835-46796-1
GitHubで編集を提案

Discussion