← All lessons
Advanced Java · Lesson 6 of 9

The JVM and memory

java starts the JVM, the Java Virtual Machine. It loads your classes' bytecode, runs it, and watches which methods run most. Those "hot" methods it compiles to real machine code while the program runs (the JIT, just-in-time compiler), so a Java program gets faster in its first seconds or minutes as it warms up. That's also why one quick timing of a piece of Java code can mislead.

Stack and heap

The JVM uses memory in two main places:

  • The stack: each thread has its own. Every method call gets a frame on it holding its parameters and local variables (simple values like int, and references). When the method returns, its frame is thrown away. Fast and automatic.
  • The heap: shared by all threads. Every object made with new lives here, however small. Variables on the stack hold references pointing into the heap.

So in Student s = new Student("Ana", 91); inside a method, the reference s sits in that method's stack frame and the Student object sits on the heap. When the method returns, s disappears, but the object stays until nothing refers to it any more.

Each call takes a frame, so a recursion that never stops eats the whole stack and the JVM throws StackOverflowError. The stack trace shows the same line repeated hundreds of times:

Java
public class Main {
    static int depth = 0;
    static void dive() { depth++; dive(); }

    public static void main(String[] args) {
        try {
            dive();
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError after many calls: " + (depth > 1000));
        }
    }
}
Prints
StackOverflowError after many calls: true

Garbage collection

You never free memory in Java. The garbage collector (GC) finds objects that nothing can reach any more (no variable, field or collection refers to them, directly or through others) and reclaims their space. It splits the heap into generations because most objects die young: a young area is collected often and cheaply, and objects that survive several collections move to an old area that's collected less often. Modern collectors (G1, the default, and ZGC for very large heaps) do most of their work alongside your program, with short pauses.

Memory leaks

A GC can't free what's still reachable, so Java programs leak memory by holding on to things they no longer need. The classic leak is a collection that only grows: a cache with no limit, a list of listeners never removed, a static map of every request. Once the heap is full and the GC can't free enough, the JVM throws OutOfMemoryError.

Log
Exception in thread "http-worker-12" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.Arrays.copyOf(Arrays.java:3512)
	at java.base/java.util.ArrayList.grow(ArrayList.java:237)
	at shop.AuditLog.record(AuditLog.java:31)
	at shop.CheckoutService.pay(CheckoutService.java:88)

The line that throws is just where memory ran out, not necessarily the leak, but a collection growing in your own code (AuditLog.record adding to a list) is a strong clue. A heap dump taken at that moment shows which objects fill the heap and what keeps them alive. A bounded cache stops one kind of leak at the source:

Java
public class Main {
    static class Recent<K, V> extends LinkedHashMap<K, V> {
        private final int max;
        Recent(int max) { super(16, 0.75f, true); this.max = max; }
        @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
    }

    public static void main(String[] args) {
        Recent<String, Integer> cache = new Recent<>(2);
        cache.put("a", 1);
        cache.put("b", 2);
        cache.get("a");
        cache.put("c", 3);
        System.out.println(cache.keySet());
    }
}
Prints
[a, c]

This LRU cache (least recently used) keeps at most two entries and drops the one used longest ago: reading a made b the oldest, so b went when c arrived.

Settings and tools

-Xmx sets the largest heap (java -Xmx2g -jar app.jar), -Xss the stack size per thread. The JDK's tools look inside a running JVM by its process id: jcmd <pid> GC.heap_info for memory, jcmd <pid> Thread.print (or jstack) for a thread dump showing what every thread is doing (the first stop for a hung program), and jcmd <pid> GC.heap_dump for a heap dump. Starting with -XX:+HeapDumpOnOutOfMemoryError writes one automatically when it matters most.

Strings are immutable and the JVM shares identical string literals, so "duck" == "duck" happens to be true. Never rely on it; text from a file or a user is a new object, and only equals is right.

Practice

In void m() { Student s = new Student(); }, where do s and the Student object live?

More info

Quick reference

JVM / bytecode / JITThe machine that runs .class files, compiling hot code as it goes.
stackPer thread: one frame per call, with locals and references.
heapShared: every object made with new.
garbage collectionFrees objects nothing can reach; young and old generations.
memory leakKeeping references you no longer need (growing caches and lists).
StackOverflowError / OutOfMemoryErrorToo deep a recursion / the heap is full.
-Xmx / -XssMax heap / stack size per thread.
jcmd <pid> Thread.print / GC.heap_dumpA thread dump / a heap dump.

Related courses