Skip to content

JVM (Java Virtual Machine): What It Is and How It Works

A machine of smoked glass with steel edges on light sand grey, with “JVM” etched into its glass lid: a card with a grid of small square holes sits in the slot on the left, and thin lines of light lead from it to a glowing amber core in the middle

The Java Virtual Machine, or JVM for short, is the program that runs your Java programs: it loads classes, translates the bytecode of these classes into machine code, and cleans up memory that is no longer needed. I’ll show you how it does that using a small program – with the JVM’s own output at every stage.

In this article, you will learn:

  • what the JVM is and how the JVM, JRE, and JDK differ,
  • what a .class file contains and how the JVM executes bytecode,
  • how the JVM loads, links, and initializes classes,
  • whether Java is compiled or interpreted – and what the JIT compiler does along the way,
  • where objects, method calls, and classes live in memory and how the garbage collector cleans up,
  • which options and tools you can use to watch a JVM at work.

What Is the JVM?

The JVM is a program that loads and runs .class files. On your computer, it is called java: when you type java Hello, you start a JVM, and it runs the class Hello.

The machine is called virtual because it behaves like a computer with its own instruction set. Its machine language is bytecode, which the Java compiler javac generates from your source code. You don’t need a processor that understands bytecode: the JVM translates it at runtime into the instructions of the processor it runs on – into x64 instructions on a computer with an Intel or AMD processor, and into AArch64 instructions on a Mac with Apple silicon.

Three things go by the name “JVM”:

  • The specification: The Java Virtual Machine Specification defines what every JVM must be able to do: the format of .class files, the bytecode instructions, how classes are loaded. What the specification does not define, however, is how a JVM divides up its memory, which garbage collector it uses, and whether it interprets bytecode or translates it into machine code – it leaves that to the implementations.
  • An implementation: a program that implements the specification. The JVM of the OpenJDK is such an implementation – it is called HotSpot. The section JVM Implementations lists the other implementations.
  • An instance: the running process that executes your program. Every call to java starts a new instance, and several instances can run side by side on one machine.

Why the detour via a virtual machine? javac generates bytecode that is not tied to any processor or operating system. The same .class file therefore runs on every platform for which there is a JVM – “Write once, run anywhere”:

javac translates Hello.java into Hello.class. The same .class file runs on a JVM for Linux x64, one for macOS AArch64, and one for Windows x64, and each JVM generates machine code for its processor and operating system
One .class file, three JVMs, three kinds of machine code

JVM, JRE, and JDK: What Is the Difference?

The three abbreviations describe three layers, each of which contains the previous one:

  • The JVM executes bytecode.
  • The JRE (Java Runtime Environment) is the JVM plus the class library – String, ArrayList, HttpClient, and all the other classes of the Java API. With a JRE, you can run a Java program, but not compile it.
  • The JDK (Java Development Kit) is the JRE plus the tools: the compiler javac, the disassembler javap, the diagnostic tool jcmd, jlink, jfr, and several more.
Three nested boxes: the JVM with class loader, interpreter, JIT compiler, and garbage collector sits inside the JRE, which adds the class library; the JRE sits inside the JDK, which adds the tools javac, javap, jcmd, jlink, and jfr
JDK, JRE, and JVM: each layer contains the previous one

Up to Java 8, every JDK contained the JRE in a subdirectory jre. Since Java 9, this directory no longer exists, because JEP 220 gave the JDK and the JRE the same structure: that of a run-time image, i.e., a directory with the java command, the JVM, and the modules of the class library. Since then, a JDK has been a run-time image that also contains the development tools.

Nevertheless, some vendors still offer a JRE for download, e.g., Eclipse Temurin and BellSoft Liberica: a run-time image without the tools. If your application only needs to run, for example on a server or in a container image, such a JRE is enough. It gets even leaner if you use jlink to build your own run-time image – with only those modules that your application needs.

You can find my recommendation for which JDK to install in the section Which Distribution? in the article on Java versions and LTS.

The Example in This Article

A program that adds up the areas of ten million rectangles accompanies us through the rest of the article. A rectangle is a record with a width and a height:

public record Rectangle(int width, int height) {

  public int area() {
    return width * height;
  }
}

The class TotalArea creates a new list of 1,000 rectangles in each of 10,000 rounds and adds up their areas:

public class TotalArea {

  private static final int ROUNDS = 10_000;
  private static final int RECTANGLES_PER_ROUND = 1_000;

  static void main() {
    long total = 0;
    for (int round = 0; round < ROUNDS; round++) {
      List<Rectangle> rectangles = createRectangles();
      total += sumOfAreas(rectangles);
    }
    System.out.println("Total area: " + total);
  }

  private static List<Rectangle> createRectangles() {
    List<Rectangle> rectangles = new ArrayList<>();
    for (int i = 0; i < RECTANGLES_PER_ROUND; i++) {
      rectangles.add(new Rectangle(i % 100 + 1, i % 50 + 1));
    }
    return rectangles;
  }

  private static long sumOfAreas(List<Rectangle> rectangles) {
    long sum = 0;
    for (Rectangle rectangle : rectangles) {
      sum += rectangle.area();
    }
    return sum;
  }
}

You can find the complete code in the GitHub repository java-jvm, in the package eu.happycoders.jvm. After running mvn compile, the classes are in target/classes; the script record-outputs.sh runs all the commands whose output I show in this article and saves the results in the results/ directory. All output comes from OpenJDK 27 (build 27+35) on a Mac with an Apple M5 Pro.

I start the program from the compiled classes, not with java TotalArea.java: in source-launcher mode, the JVM would first load and run the compiler javac, and its classes and compilations would then show up in every log.

The first output doesn’t need the program yet. java -version shows which JVM the java command starts:

$ java -version
openjdk version "27" 2026-09-15
OpenJDK Runtime Environment (build 27+35-2325)
OpenJDK 64-Bit Server VM (build 27+35-2325, mixed mode, sharing)

The last line describes the JVM, and I explain four of its details in their own sections of this article:

  • OpenJDK 64-Bit – the JVM of the OpenJDK for 64-bit processors, i.e., HotSpot (section JVM Implementations).
  • Server VM – a HotSpot JVM with both JIT compilers, C1 and C2 (section Interpreter and JIT Compiler).
  • mixed mode – the interpreter and the JIT compiler work together. With the option -Xint, which switches off the JIT compiler, this would read interpreted mode (section Is Java Compiled or Interpreted?).
  • sharing – the JVM loads the JDK’s classes from a prepared archive, the Class-Data Sharing archive (section Startup and Warmup).

How Does the JVM Work? An Overview

The JVM consists of several parts: class loader, interpreter, JIT compiler, and garbage collector, plus memory areas such as the heap, the stack, and the metaspace. Before we look at them one by one, here is the example’s path through the JVM in five steps:

  1. javac translates TotalArea.java and Rectangle.java into two .class files.
  2. The class loader loads the classes as soon as the program needs them; the JVM links and initializes them and stores their metadata in the metaspace.
  3. The interpreter executes the bytecode, instruction by instruction. Every method call gets a frame on the stack of its thread.
  4. The JIT compiler translates methods that run often into machine code and stores it in the code cache. From then on, the processor executes these methods directly, without the interpreter.
  5. Each round of the program creates an ArrayList and 1,000 Rectangle objects on the heap. After the round, no variable refers to them anymore, and the garbage collector can free their memory.

The figure shows these parts with the names they have in HotSpot – on the left the execution, on the right the memory areas it fills. At the bottom is the processor, which executes the machine code from the code cache. Every part of the JVM has its own section in this article:

On the left, the execution from top to bottom: class files, class loader, interpreter, JIT compiler with C1 and C2. On the right, the memory areas: heap with garbage collector, metaspace, thread stacks, code cache. Arrows lead from the class loader to the metaspace, from the interpreter to the thread stacks, and from the JIT compiler to the code cache. An arrow leads from the code cache to the processor at the bottom left, which executes the machine code directly
The parts of the JVM and the memory areas they fill

Bytecode: The Language of the JVM

A .class file contains everything the JVM needs to know about a class: its name, the version of the class file format, the constant pool with all the names, types, and constants the code refers to, and the fields and the methods with their bytecode. The format is described in chapter 4 of the JVM specification.

You can read the bytecode with javap, the JDK’s disassembler. Without options, javap shows the declaration of the class and the signatures of its fields, constructors, and methods, but no code. With the option -c, it also prints the bytecode of every method. In both cases, javap omits private fields and methods; it only shows them with the option -p. For the area() method, the bytecode looks like this:

$ javap -c -cp target/classes eu.happycoders.jvm.Rectangle
...
  public int area();
    Code:
         0: aload_0
         1: getfield      #7                  // Field width:I
         4: aload_0
         5: getfield      #13                 // Field height:I
         8: imul
         9: ireturn

The number before each instruction is its position in the method’s bytecode, in bytes. #7 and #13 are entries in the constant pool; the comment after them – field name and type, I for int – is added by javap.

I’ve left out of the listing the other methods that javac automatically generated for the Rectangle record: the constructor, the accessor methods width() and height(), and toString(), hashCode(), and equals(). At their core, the last three consist of a single instruction, invokedynamic, which determines the implementation only at runtime. I explain what happens there in the sections How the JVM Executes a Lambda in the article on lambda expressions and Since Java 9: invokedynamic in the article on converting int to String.

The JVM as a Stack Machine

The JVM’s instructions don’t work with registers like those of a processor, but with an operand stack: they take their operands from there and put their result back there. Every method call gets its own operand stack and its own local variables. In an instance method, local variable 0 holds the reference to the object, this.

This is how area() calculates:

  1. aload_0 pushes the reference from local variable 0, i.e., this, onto the stack.
  2. getfield width pops the reference to this off the stack again, reads the field width from the object it points to, and pushes its value onto the stack.
  3. aload_0 pushes this onto the stack once more.
  4. getfield height pops the reference off the stack again, reads the field height, and pushes its value onto the stack.
  5. imul pops the top two int values off the stack – these are now the values of the fields width and height – calculates their product, and pushes it onto the stack.
  6. ireturn pops the product off the stack again and returns it to the caller of the method.

The following figure shows what the operand stack looks like after each instruction, for a rectangle with a width of 60 and a height of 10. The steps are numbered as in the list above; as in the javap listing, the number before each instruction is its position in the bytecode:

Six columns, one per instruction of area(), with the step number, position, and instruction at the top and the operand stack below: after aload_0 this, after getfield width 60, after aload_0 60 and this, after getfield height 60 and 10, after imul 600, after ireturn the stack is empty and 600 has been returned to the caller
The operand stack after each instruction of area() for a rectangle with width 60 and height 10

The Version of the .class File

With the option -v instead of -c, javap shows the header of the .class file:

$ javap -v -cp target/classes eu.happycoders.jvm.Rectangle
...
public final class eu.happycoders.jvm.Rectangle extends java.lang.Record
  minor version: 0
  major version: 69

69 is the class file format version of Java 25. I compiled the example with Java 27, but with the compiler option -target 25 – so it also runs on Java 25. The count started at 45 with Java 1.0, and since Java 1.2, every release has increased the number by one. The version is therefore the Java version plus 44: without -target, a javac from Java 27 writes version 71.

A JVM runs .class files up to its own version, but no newer ones. A Java 21 JVM, for example, knows class file versions up to 65. If you start the example with a Java 21 JVM, it aborts while loading the main class TotalArea with an UnsupportedClassVersionError; the error message names both version numbers:

$ java -cp target/classes eu.happycoders.jvm.TotalArea
Error: LinkageError occurred while loading main class eu.happycoders.jvm.TotalArea
    java.lang.UnsupportedClassVersionError: eu/happycoders/jvm/TotalArea has been compiled by a more recent version of the Java Runtime (class file version 69.0), this version of the Java Runtime only recognizes class file versions up to 65.0

Loading, Linking, and Initializing Classes

The JVM does not load a class at startup, but only when the program needs it. Before its code can run, the class must go through three steps defined in chapter 5 of the JVM specification:

  1. Loading: A class loader finds the .class file, and the JVM creates the class from it.
  2. Linking, in three substeps:
    • Verification checks whether the bytecode complies with the rules of the specification – e.g., that no instruction uses an int where it expects an object reference: getfield, for instance, needs an object reference on the stack, not a number.
    • Preparation creates the static fields and sets them to their default values (0 for numbers, false for booleans, null for object references).
    • Resolution replaces the symbolic references from the constant pool with direct references. Neither has anything to do with object references: a symbolic reference names a class, a field, or a method, e.g., #7 // Field width:I. A direct reference tells the JVM where to find what is named – for a field like width, that can be its position in the object, in bytes. The JVM may postpone resolution until an instruction uses the symbolic reference for the first time.
  3. Initialization: The JVM runs the class initializer <clinit> – it contains the static blocks and the assignments to static fields. This happens when the program first actively uses the class: creates an object of it, calls a static method, or reads or writes a static field.
Three steps from top to bottom: Loading finds the class file and creates the class. Linking consists of verification, preparation, and resolution. Initialization runs the class initializer clinit: static initializers and field assignments
Loading, linking, initialization

The JVM initializes each class exactly once, even if several threads access it at the same time. The Initialization-on-Demand Holder Idiom builds on this guarantee; with it, you can create a singleton lazily without synchronized.

How the JVM finds and calls the main() method of the first class is described in the section How the JVM Calls the main() Method in the article on the main() method.

The Three Class Loaders

Loading is the job of the class loaders – the JVM contains the following three:

  • The bootstrap class loader loads the core modules of the JDK, first and foremost java.base with classes such as java.lang.String and java.util.ArrayList. It has no representation of its own in Java: String.class.getClassLoader() returns null.
  • The platform class loader loads further modules of the JDK, e.g., java.sql and java.net.http. It replaced the former extension class loader in Java 9.
  • The application class loader, also called the system class loader, loads your application’s classes from the class path and the module path – in our example, TotalArea and Rectangle from target/classes.

Every class loader except the bootstrap class loader has a parent: the parent of the application class loader is the platform class loader, whose parent is the bootstrap class loader.

Three boxes on top of each other: at the top the bootstrap class loader, loads the core modules of the JDK such as java.base, java.logging, and java.xml; in the middle the platform class loader, loads further modules of the JDK such as java.sql and java.net.http; at the bottom the application class loader, loads from the class and module path, in the example TotalArea and Rectangle. Arrows labeled Parent lead from the application to the platform and from the platform to the bootstrap class loader
The three built-in class loaders and their parents

If the code of a class needs another class, the JVM asks the class loader that loaded the requesting class. In our example, that is the application class loader for TotalArea and Rectangle – so every request of the example arrives there first.

Before Java 9, every built-in class loader first passed a request on to its parent: the application class loader to the extension class loader, which passed it on to the bootstrap class loader. Only if the parent didn’t find the class did a class loader search for it itself. So the request went from bottom to top, the search from top to bottom.

Since Java 9, this order only applies to classes whose package is not in any module – i.e., to classes from the class path. Classes from modules – those of the JDK and those from the module path – are handled differently.

The three class loaders share a table that maps each package to its module; the JVM fills it at startup from the module descriptors (module-info.class) of all modules. The class loader that receives the request first looks up the package in this table and then passes the request on directly to the class loader that loads the module. There is no separate class loader per module: the bootstrap class loader, for example, loads java.logging and java.xml in addition to java.base.

If TotalArea, for example, asks for java.util.ArrayList, the request arrives at the application class loader. The package java.util belongs to the module java.base, so the application class loader passes the request on directly to the bootstrap class loader, bypassing the platform class loader. If, on the other hand, TotalArea asks for Rectangle, the application class loader finds no module with the package eu.happycoders.jvm. It therefore asks its parent first, which in turn asks the bootstrap class loader, and since neither of them knows the class, the application class loader finally loads it itself from the class path.

Two flows, one above the other. At the top, a class from a module, java.util.ArrayList: TotalArea needs ArrayList, the request arrives at the application class loader (1). It looks up java.util in the table package → module (2), which maps java.util to the module java.base and thus to the bootstrap class loader, and passes the request on directly to the bootstrap class loader (3), which loads ArrayList from java.base; the platform class loader is skipped. At the bottom, a class from the class path, eu.happycoders.jvm.Rectangle: TotalArea needs Rectangle (1), the application class loader doesn’t find eu.happycoders.jvm in the table (2), asks its parent, the platform class loader (3), which asks the bootstrap class loader (4); neither knows Rectangle, and the application class loader loads the class itself from target/classes (5)
Since Java 9: the request for a class from a module (top) and for one from the class path (bottom). Before Java 9, all requests went through the parents as at the bottom.

For a class from the class path, this detour via the parents is unnecessary in almost all cases: the platform class loader has no class path, and the bootstrap class loader only has one if you append one with -Xbootclasspath/a. The order dates from the time before modules. Back then, it prevented a class of the same name from the class path from replacing a class of the JDK. Today, the modules prevent that: a class java.lang.String on the class path would never be loaded, because the request for it goes directly to the bootstrap class loader via the package java.lang.

Which Classes the Example Loads

The option -Xlog:class+load shows which classes the JVM loads and from where. I have shortened the output, including the path to the repository, and sorted the lines by their source:

$ java -Xlog:class+load -cp target/classes eu.happycoders.jvm.TotalArea
[0.006s][info][class,load] java.lang.Object source: shared objects file
[0.006s][info][class,load] java.io.Serializable source: shared objects file
...
[0.013s][info][class,load] jdk.internal.loader.URLClassPath$FileLoader source: jrt:/java.base
[0.013s][info][class,load] java.lang.InterruptedException source: jrt:/java.base
...
[0.013s][info][class,load] eu.happycoders.jvm.TotalArea source: file:/.../target/classes/
[0.014s][info][class,load] eu.happycoders.jvm.Rectangle source: file:/.../target/classes/
...
[0.066s][info][class,load] java.lang.invoke.StringConcatFactory source: shared objects file
...
[0.069s][info][class,load] java.lang.invoke.LambdaForm$MH/0x00007ff801040800 source: __JVM_LookupDefineClass__
...

In total, the small program loads 619 classes:

  • 612 classes such as java.lang.Object and java.io.Serializable from the shared objects file – the CDS archive (Class-Data Sharing), which the word sharing in the output of java -version refers to and which I explain in the section Startup and Warmup,
  • four classes such as jdk.internal.loader.URLClassPath$FileLoader and java.lang.InterruptedException from the JDK’s run-time image (jrt:/java.base),
  • two classes from the example, TotalArea and Rectangle from target/classes,
  • one class that the JVM generates itself at runtime, shortly after java.lang.invoke.StringConcatFactory: LambdaForm$MH for the string concatenation in the println() line.

If you start the program with -Xshare:off, i.e., without the CDS archive, the JVM loads 632 classes: 629 from the run-time image and, as before, the two classes of the example and the self-generated LambdaForm$MH.

The article on Ahead-of-Time Class Loading & Linking shows how you can move this loading work to before the start so that your application starts faster.

Interpreter and JIT Compiler: How the JVM Executes Bytecode

HotSpot first executes every method in the interpreter, instruction by instruction, as described in the section on bytecode. In doing so, it counts how often the method is called and how often its loops iterate.

Interpreting is slow. Methods that run often – hot methods – are therefore translated into machine code at runtime by the JIT compiler (just-in-time compiler). HotSpot has two compilers: C1 translates quickly and optimizes little; C2 takes longer and generates faster code.

Tiered Compilation: The Five Levels

The two compilers work together in five levels, which HotSpot calls tiered compilation:

LevelWhoWhat
0Interpreterexecutes bytecode and counts calls and loop iterations
1C1machine code without profiling
2C1machine code that counts calls and loop iterations
3C1machine code that also collects a complete profile
4C2optimized machine code based on the profile

In addition to the number of calls and loop iterations, the profile collected at level 3 contains further details, e.g., which branches the program takes and which classes arrive at a call site where several classes are possible.

The usual path of a hot method – i.e., a method that the program executes often – leads from level 0 via level 3 to level 4. The JVM chooses level 2 when C2 is busy; level 1 when a method is so simple that C2 wouldn’t translate it any better than C1: a getter or setter, or a method that only returns a constant.

Three boxes from left to right: level 0, the interpreter, executes bytecode and counts; once a method has been executed often, C1 compiles it at level 3 with a profile; if it continues to be executed often, C2 compiles it at level 4, optimized by the profile. An arrow leads from level 4 back to level 0: deoptimization, when an assumption from the profile no longer holds
The usual path of a hot method through the levels – and back

Thresholds control when a method counts as hot. -XX:+PrintFlagsFinal shows their default values: after 200 calls (Tier3InvocationThreshold), C1 compiles a method at level 3; after another 5,000 calls (Tier4InvocationThreshold), C2 compiles it at level 4. Loop iterations count too, and if the compilers are busy, the JVM raises the thresholds.

Watching the JIT Compiler

With -XX:+PrintCompilation, the JVM writes every compilation to the console. For the example, that’s 81 lines; 18 concern the example’s methods, the rest JDK methods such as java.lang.String::hashCode. Here are the lines for area():

$ java -XX:+PrintCompilation -cp target/classes eu.happycoders.jvm.TotalArea
...
12   18       3       eu.happycoders.jvm.Rectangle::area (10 bytes)
12   20       4       eu.happycoders.jvm.Rectangle::area (10 bytes)
12   18       3       eu.happycoders.jvm.Rectangle::area (10 bytes)   made not entrant: not used
...

The columns, from left to right:

  1. 12 – the time since the JVM started, in milliseconds.
  2. 18 – the sequence number of the compilation.
  3. Attributes, empty here. %, for example, stands for an OSR compilation (see below), n for a native method, s for a synchronized method.
  4. 3 – the level.
  5. The method and the size of its bytecode: 10 bytes, positions 0 to 9 from the javap listing.

The second line shows compilation number 20 of area() at level 4 – in the same millisecond as the level 3 compilation in the first line. The reason: if a method contains nothing worth profiling – area() has neither a branch nor a method call – it moves from level 3 to level 4 without a threshold.

As soon as the level 4 code is ready, the JVM no longer needs the level 3 code: made not entrant: not used in the third line means that no new call enters it anymore. The line carries the number 18 because it doesn’t report a new compilation, but refers to the code of compilation 18 from the first line. The code isn’t deleted yet, though: threads that are currently running in it run it to completion. Only when no thread uses it anymore does the JVM remove it from the code cache during a later garbage collection.

The following output shows a second kind of compilation. Normally, the JVM compiles a method in the background while it continues to run in the interpreter; only the next call of the method uses the machine code. With long loops, the JVM doesn’t wait that long: after 60,000 loop iterations (Tier3BackEdgeThreshold), it compiles the method while it is running and switches to the machine code in the middle of the loop. This switch is called on-stack replacement (OSR) and is marked with % in the log. createRectangles() and sumOfAreas() reach this threshold around their 60th call, because their loops run 1,000 times on each call.

The number after the @ is the position in the bytecode at which the machine code takes over, here position 10:

15   31 %     3       eu.happycoders.jvm.TotalArea::createRectangles @ 10 (51 bytes)
16   35 %     4       eu.happycoders.jvm.TotalArea::createRectangles @ 10 (51 bytes)

What C2 Does with the Profile

With the profile data, C2 optimizes for what the program actually does at runtime. Among other things:

  • It inlines small methods into their callers (inlining).
  • It removes code whose result nobody uses.
  • It computes expressions whose values javac doesn’t know yet but that are fixed at runtime – e.g., an expression like CORES * 2, where CORES is defined as static final int CORES = Runtime.getRuntime().availableProcessors().
  • It translates loops into SIMD instructions that process several values at once.

In doing so, C2 optimizes based on assumptions: e.g., that objects of the same class always arrive at a call site, or that a branch is never taken. If an assumption no longer holds later, the JVM discards the machine code and continues execution in the interpreter. This deoptimization is the arrow back in the figure above; if the method is still hot, the JVM recompiles it later – based on new assumptions.

The JVM stores the machine code in the code cache, a separate memory area outside the heap. On my Mac, it reserves 240 MB for it (ReservedCodeCacheSize). The example occupies a mere 1.2 MB of that. My IntelliJ IDEA occupies 149 MB after two days of running and 277 MB at peak – JetBrains sets its code cache to 512 MB. jcmd <pid> Compiler.codecache shows you how much your application needs while it is running.

If one of the areas of the code cache is full, the JVM reports, e.g., CodeHeap 'non-profiled nmethods' is full. Compiler has been disabled. Until a garbage collection has removed machine code that is no longer needed, the JIT compiler then doesn’t translate any further methods.

Is Java Compiled or Interpreted?

Both – as the previous sections have shown. Java is compiled twice – by javac into bytecode and by the JIT compiler into machine code – and interpreted in between:

StepToolWhen
Source code → bytecodejavac compilerbefore the start, once
Execute bytecodeInterpreterfrom the start, for every method
Bytecode → machine codeJIT compiler (C1, C2)at runtime, for hot methods

With -Xint, you switch off the JIT compiler; java -version then shows interpreted mode, and the JVM interprets the entire program.

Memory: Heap, Stack, and Metaspace

The memory of a JVM consists of several areas with different tasks:

  • The heap contains all objects and arrays – in the example, the ArrayList and Rectangle objects. All threads share the heap; it is cleaned up by the garbage collector.
  • Every thread has its own stack. Every method call creates a frame on it, with the local variables and the operand stack of the method. A local variable of a primitive type is stored with its value in the frame; for an object, the frame only holds the reference.
  • The metaspace contains the metadata of the classes: their methods, their bytecode, the constant pool. The specification calls this area the method area. Since Java 8, HotSpot has placed it in native memory outside the heap; before that, it was located in the heap as the permanent generation (JEP 122).
  • The code cache contains the JIT compiler’s machine code.

This is what it looks like for the example while sumOfAreas() calls the area() method of a Rectangle object:

On the left, the stack of the main thread with three frames: at the top area() with this, below it sumOfAreas() with rectangles, sum, and rectangle, at the bottom main() with total, round, and rectangles. The references rectangles from both frames point to an ArrayList on the heap, this and rectangle to the same Rectangle object. Below that, the code cache with the machine code of area() and the metaspace with the classes TotalArea, Rectangle, and ArrayList; a dashed arrow leads from the right-hand Rectangle object into the metaspace
Stack, heap, metaspace, and code cache while area() is running

On the stack of the main thread, three frames lie on top of each other: main() at the bottom, sumOfAreas() above it, and area(), the currently running method, at the top. total and round in main() and sum in sumOfAreas() are primitive variables; their value is stored directly in the frame. The two variables rectangles in main() and sumOfAreas(), on the other hand, contain a reference – both to the same ArrayList on the heap, which in turn refers to its 1,000 Rectangle objects. rectangle in sumOfAreas() and this in area() also point to the same object: the rectangle whose area is currently being calculated.

The machine code of area() is in the code cache, and the classes of the objects are in the metaspace. Every object refers to its class – the dashed arrow from the right-hand Rectangle, which stands in for all objects here, shows this.

You control the size of the areas with these options:

  • -Xmx sets the maximum size of the heap. Without this option, HotSpot takes a quarter of the main memory (MaxRAMPercentage), i.e., 16 GB on my Mac with 64 GB.
  • -Xms sets the minimum and initial size of the heap. On my JDK 27, the heap starts with 8 MB without this option – since Java 26, the initial size has been the minimum size.
  • -Xss sets the size of the stack per thread. The default value depends on the operating system and the processor: 1 MB on Windows and on Linux with an x64 processor, just under 2 MB on Linux with an ARM processor, and 2 MB on my Mac with Apple silicon.

If an area overflows, the JVM throws an error:

  • If the stack of a thread is full – usually due to endless recursion – it throws a StackOverflowError.
  • If it finds no space on the heap for a new object, even after the garbage collector has cleaned up, it throws an OutOfMemoryError with the message “Java heap space”.
  • If the metaspace is full, it also throws an OutOfMemoryError, with the message “Metaspace”.

If you programmed before Java 8, you will remember the message “OutOfMemoryError: PermGen space”: the permanent generation, in which the classes were stored back then, had a fixed upper limit. The metaspace, on the other hand, grows as needed – without -XX:MaxMetaspaceSize, without limit.

Garbage Collection

In Java, you don’t free memory yourself. The garbage collector (GC) takes care of that. Figuratively speaking, it collects the garbage. Technically, however, it works the other way around: it doesn’t look for the garbage, but for those objects that the program can still reach. To do this, it follows all references, starting from local variables and static fields. Whatever it does not find this way is garbage.

Most objects are short-lived: in the example, each list, together with its 1,000 rectangles, is unreachable after one round. And that applies not only to the example, but to almost all applications – this observation is called the weak generational hypothesis. Most garbage collectors build on it: they divide the heap into a young and an old generation. The JVM creates new objects in the young generation.

When the young generation is full, the GC copies the objects that are still reachable into a survivor area – or, if they have already survived often enough, into the old generation. It then frees the previous area. And because most objects are short-lived, there are usually only a few objects to copy, and the GC is done quickly. It cleans up the old generation, where the long-lived objects accumulate, only rarely.

The option -Xlog:gc shows what the garbage collector does:

$ java -Xlog:gc -cp target/classes eu.happycoders.jvm.TotalArea
[0.003s][info][gc] Using G1
[0.019s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 9M->1M(24M) 0.278ms
[0.022s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 9M->1M(32M) 0.161ms
...
[0.049s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 49M->1M(288M) 0.233ms
Total area: 14960000000

The first line names the collector: G1, the default. Every further line is a garbage collection. After the details in square brackets – time since the JVM started, log level, and log tag – come these columns:

  • GC(0) – the sequence number.
  • Pause Young (Normal) – a pause in which G1 cleans up the young generation.
  • (G1 Evacuation Pause) – the cause: there is no more room for new objects in the young generation.
  • 9M->1M(24M) – the occupied heap before and after the collection and, in parentheses, the current size of the heap.
  • 0.278ms – the duration of the pause.

After each of the seven collections, only 1 MB is still occupied, because the Rectangle objects of the past rounds are no longer reachable and have been cleaned up by the garbage collector. The total size of the heap has grown to 288 MB in the process, because G1 enlarges it as needed, up to the limit set by -Xmx. Without -Xmx, this limit is a quarter of the main memory – i.e., 16 GB on my Mac with 64 GB. With -Xmx32m, the same program needs only 32 MB of heap, but 25 collections.

The OpenJDK contains five garbage collectors for production use:

CollectorGoalOptionDefault
Seriallittle overhead, one GC thread-XX:+UseSerialGCno
Parallelmaximum throughput-XX:+UseParallelGCno
G1balance of throughput and short pauses-XX:+UseG1GCon servers since Java 9, everywhere since Java 27
ZGCminimal pauses, even with a very large heap-XX:+UseZGCno
Shenandoahminimal pauses, regardless of the heap size-XX:+UseShenandoahGCno

Shenandoah is not included in every build: with -XX:+UseShenandoahGC, my OpenJDK 27 from Oracle refuses to start and reports “Option -XX:+UseShenandoahGC not supported”. In addition, there is Epsilon, a collector that doesn’t free any memory – for tests and measurements, enabled with -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC (Java 11).

You can find more on the individual collectors in the sections on ZGC and Shenandoah in Java 15, Generational ZGC in Java 21, and ZGC and Shenandoah in Java 28. You can tell from a Java Flight Recorder recording whether the GC slows down your application – the section Garbage Collections: Is the GC Slowing Down the Application? in the article on JDK Mission Control shows how.

Threads and Native Code

A thread that you create with new Thread() is a platform thread: behind it is an operating system thread, and its stack is a fixed memory area outside the heap that the operating system reserves when the thread starts. Since Java 21, there are also virtual threads. The JVM itself distributes them across a few platform threads and stores their stack on the heap while they are waiting. The article on virtual threads explains how that works and where it reaches its limits.

When a thread locks an object with synchronized, the JVM records this directly on the object: two bits in the mark word, a part of the object header, indicate whether the object is locked. The thread itself keeps track of the locks it holds: it stores a reference to the object in a small list of the objects it has locked, its lock stack. Only when a second thread waits for the same lock or a thread calls wait() does the JVM create a separate data structure, a monitor, in which it manages the waiting threads.

Java code can also call functions outside the JVM, e.g., operating system libraries written in C. Since Java 22, this has been possible with the Foreign Function & Memory API (FFM API). Before that, there was only the Java Native Interface (JNI), which many libraries still use today. The section Difference Between the FFM API and JNI in the article on the FFM API describes what the FFM API does better.

Startup and Warmup: CDS and the AOT Cache

Everything I have described in this article so far happens all over again at every start: the JVM loads and links – depending on the size of the application – hundreds to tens of thousands of classes, interprets the code, collects profiles, and compiles the code – first with C1 and then with C2. Only then does the program run at full speed.

With two mechanisms, you can move parts of this work to before the start of the application.

The older one is Class-Data Sharing (CDS): the JVM doesn’t read classes from the .class files, but from an archive in which the classes are already parsed and converted into the JVM’s internal form. Since Java 10, such an archive can also contain the application’s classes (AppCDS). Since Java 12, the JDK has shipped with an archive for its own classes – hence the 612 classes from the shared objects file in the log and the sharing in the output of java -version. Since Java 13, the archive can be created at the end of a program run, and since Java 19, also automatically.

The newer mechanism is the AOT cache. It builds on CDS and goes further in four steps:

GraalVM Native Image takes a completely different route: it compiles the application at build time – together with parts of the runtime environment – into an executable file. The section And What About GraalVM Native Image and jaotc? in the article on Ahead-of-Time Code Compilation describes the consequences.

JVM Implementations: HotSpot, OpenJ9, GraalVM

There are several implementations of the JVM specification:

  • HotSpot is the JVM of the OpenJDK. The widespread distributions – Eclipse Temurin, Amazon Corretto, Azul Zulu, BellSoft Liberica, Oracle JDK – are based on the OpenJDK and thus come with HotSpot.
  • Eclipse OpenJ9 is a separate JVM implementation developed by IBM. It is part of the IBM Semeru Runtimes.
  • GraalVM is a JDK with its own JIT compiler written in Java, the Graal compiler. GraalVM also includes the Native Image compiler from the previous section. Up to Java 26, the Graal compiler could still be plugged into a regular OpenJDK – Java 27 removed the interface for it, see Removal of the JVM Compiler Interface (JVMCI).

Everything I show in this article – the class loaders, the compilers C1 and C2, the collectors, and the options – describes the HotSpot JVM. You can find my recommendation for which distribution to use in the section Which Distribution? in the article on Java versions and LTS.

JVM Languages

The JVM executes .class files, not Java source code. How a .class file was created doesn’t matter – it can also come from another programming language. Languages whose compilers generate .class files are therefore called JVM languages. Three examples:

  • Kotlin is more concise than Java, distinguishes in its type system between references that may be null and those that may not, and is an officially supported language on Android.
  • Scala combines object-oriented and functional programming with a static type system.
  • Clojure is a Lisp dialect with dynamic typing in which all data structures are immutable.

By the way, Android doesn’t run Kotlin and Java code on a JVM. At build time, the tool D8 translates the .class files into DEX bytecode: a format of its own that Android’s runtime environment ART executes.

JVM Options: The Most Important Switches

When you start the JVM, you can specify various options – these fall into three groups:

  • Standard options such as -cp, -D, or -version work in every JVM; you can list them with java --help.
  • -X options such as -Xmx or -Xlog are not standardized; you list these options with java -X.
  • -XX options such as -XX:+PrintCompilation, -XX:-TieredCompilation, or -XX:MaxRAMPercentage=50 control details of HotSpot. You switch certain features on with + and off with -, and you set configuration values with =. Some options are only allowed after -XX:+UnlockExperimentalVMOptions or -XX:+UnlockDiagnosticVMOptions.

The following table shows the options from this article and a few more that you will often need. The links in the “More on this” column lead to sections of this article or to other articles that explain the respective option in more detail:

OptionEffectMore on this
-cp, -classpath, --class-path <path>class pathThe Three Class Loaders (this article)
-p, --module-path <path>module pathJava Platform Module System (other article)
-D<name>=<value>set a system property–
--add-modules <modules>add modules, e.g., incubator modulesJava Platform Module System (other article)
--add-exports, --add-opensmake a package of a module accessible to other modules or additionally open it for deep reflectionStrongly Encapsulate JDK Internals (other article)
-Xmx<size>, -Xms<size>maximum and initial heap sizeMemory (this article)
-Xss<size>stack size per threadMemory (this article)
-Xintinterpreter only, no JIT compilerIs Java Compiled or Interpreted? (this article)
-Xshare:offstart without the CDS archiveStartup and Warmup (this article)
-Xlog:class+load, -Xlog:gclog output of the JVMUnified JVM Logging (other article)
-XX:+PrintCompilationprint every JIT compilationWatching the JIT Compiler (this article)
-XX:+UseSerialGC, -XX:+UseZGC, etc.choose the garbage collectorGarbage Collection (this article)
-XX:StartFlightRecordingrecording with the Flight RecorderJava Flight Recorder (other article)
--enable-native-access, --illegal-native-accessallow native access (FFM API, JNI) for certain modules, or allow, warn about, or deny it for all othersPrepare to Restrict the Use of JNI (other article)
--enable-final-field-mutation, --illegal-final-field-mutationallow changing final fields via deep reflection for certain modules, or allow, warn about, or deny it for all othersJEP 500: Make Final Mean Final (other article)
-javaagent, -agentpathload a Java agent or native agent, e.g., for a profilerDynamic Loading of Agents (other article)
-XX:AOTCache=<file>use an AOT cacheAhead-of-Time Class Loading & Linking (other article)
-XX:+PrintFlagsFinalall -XX options with their valuessee below

On my JDK 27, -XX:+PrintFlagsFinal lists 805 options, each with its value and its origin. {default} means that the value is built in – like the share of main memory for the heap and the stack size per thread; {ergonomic} means that the JVM chose it for the machine at startup – like the maximum heap size and the garbage collector:

$ java -XX:+PrintFlagsFinal -version
...
   size_t MaxHeapSize      = 17179869184 {product} {ergonomic}
...
   double MaxRAMPercentage = 25.000000   {product} {default}
...
     intx ThreadStackSize  = 2048        {pd product} {default}
...
     bool UseG1GC          = true        {product} {ergonomic}
...

You can put options that every JVM on a machine should pick up into the environment variable JAVA_TOOL_OPTIONS. If you also specify the same option on the command line, the value from the command line applies: with JAVA_TOOL_OPTIONS=-Xmx64m and java -Xmx128m …, the heap gets 128 MB.

Looking Inside the JVM: The Tools

The JDK comes with tools that let you watch a JVM at work:

QuestionToolMore on this
What does the bytecode of a class look like?javap -cBytecode (this article)
Which threads are running, which options apply, how full is the heap?jcmd <pid> Thread.print, VM.flags, GC.heap_infoOn a Running JVM: jcmd (other article)
Where do CPU time and memory go?Java Flight RecorderJava Flight Recorder (other article)
How do I analyze a recording graphically?JDK Mission ControlJDK Mission Control (other article)
What does the JVM log?-XlogUnified JVM Logging (other article)
How fast is a piece of code?JMHJMH (other article)

jcmd without arguments lists the running JVMs with their process IDs.

All JVM Articles at a Glance

TopicArticle
Lambdas and invokedynamicJava Lambda Expressions
Starting a programJava main() Method
Class initializationInitialization-on-Demand Holder Idiom
JIT compiler and vectorizationJava Vector API
Objects on the heapJava Object Headers and Compressed Class Pointers
Compressed Oops in Java
Compact Object Headers in Java
Project Valhalla: Value Objects
ThreadsVirtual Threads in Java
Native codeJava FFM API
Startup and warmupAhead-of-Time Class Loading & Linking
Ahead-of-Time Method Profiling
Ahead-of-Time Code Compilation
Measuring and analyzingJava Flight Recorder (JFR)
JDK Mission Control (JMC)
JMH (Java Microbenchmark Harness)

Conclusion

The JVM loads classes only when the program needs them, executes their bytecode in the interpreter first, and translates the hot methods into machine code in two stages (C1 and C2). It stores objects on the heap, and the garbage collector frees what the program can no longer use. So a Java program is not completely translated into machine code before the start, but only while it runs: the JVM observes the program and decides accordingly which code it optimizes and how heavily.

If you want to know why your program starts slowly, continue reading with Ahead-of-Time Class Loading & Linking. The Java Flight Recorder shows you where CPU time and memory go, and JMH measures whether a change makes your code faster.

Did you take something away from this article? With a review on my ProvenExpert profile, you help other developers assess whether these articles are worth reading – and you help me understand which content is most useful to you.

👉 Leave a review

Want Even More Knowledge?

My blog features many articles on Java, software architecture, and performance — from foundational concepts to advanced patterns.

If you want to go deeper, check out my trainings: hands-on, easy to understand, and directly applicable to your day-to-day project work. Instead of theory, I teach principles that help you write code that is better, more maintainable, and more performant in the long run.

Explore the Java Trainings

Become a Better Java Developer

My free newsletter keeps you ahead. Modern Java: new versions & features, performance, and JVM insights – once a month.

Search