Skip to lesson

A running JVM splits its memory into a few runtime data areas, and each area has one job. Some areas are shared by every thread of the program; the others are created fresh for each thread. Knowing which is which explains most memory errors, most thread-safety rules and most interview questions in this section.

Shared areas: the heap and the method area

The JVM divides memory into areas: the heap for objects, a stack per thread for method calls, and metaspace for class information.

The heap is the memory where every object and every array lives. A JVM has one heap, and all threads of the program share it. Each new Course(...) creates its object on the heap.

Shared by all threads: the heap (objects and arrays) and Metaspace (class metadata). One set per thread: a JVM stack of frames, a program counter and a native method stack. The JVM also uses native memory outside the heap, for example for the code cache and direct buffers.

Example 1 · One heap, seen by two threads

SharedHeapDemo.javaJava
class Course {    static int coursesCreated = 0;   // one value for the whole class    String name;                     // stored inside each Course object    int fee;
    Course(String name, int fee) {        this.name = name;        this.fee = fee;        coursesCreated++;    }}
public class SharedHeapDemo {    public static void main(String[] args) throws InterruptedException {        int discount = 500;        Course java = new Course("Java", 4999);    // the object is on the heap        Course dsa = new Course("DSA", 3999);        Course sameCourse = java;
        sameCourse.fee = sameCourse.fee - discount;
        Thread printer = new Thread(() ->                System.out.println("Printer thread sees: " + java.name + " Rs " + java.fee));        printer.start();        printer.join();
        System.out.println("Main thread sees:    " + java.name + " Rs " + java.fee);        System.out.println("Other course:        " + dsa.name + " Rs " + dsa.fee);        System.out.println("Courses created:     " + Course.coursesCreated);    }}
Output
Printer thread sees: Java Rs 4499
Main thread sees:    Java Rs 4499
Other course:        DSA Rs 3999
Courses created:     2

What this code does

  • There are two Course objects on the heap but three references: java, dsa and sameCourse. Changing the fee through sameCourse changes the one object that java also points to.
  • The printer thread has its own stack, yet it reads the same heap object and sees Rs 4499. Heap objects are shared between threads.
  • discount is a local variable in main's frame. coursesCreated is a single static value for the whole class, so it counts both objects.

The method area holds information about each loaded class: the bytecode of its methods, its field names and types, and its constant pool. The JVM specification only says this area must exist. HotSpot, the JVM inside the usual OpenJDK and Oracle JDK downloads, keeps this class data in Metaspace, a region of native memory outside the heap (Java 8 and later). Because both areas are shared, an object made by one thread can be used by any other thread that holds a reference to it.

On HotSpot, the values of static fields and the String pool also sit on the heap. The lesson on Metaspace, static fields and the String pool covers them.

Per-thread areas: JVM stack, program counter, native method stack

Each thread gets three private areas when it starts. The JVM stack holds one frame for every method call that has not finished yet; a frame keeps that call's local variables and working values.

Example 2 · Each thread has its own stack of frames

ThreadAreasDemo.javaJava
import java.util.List;
public class ThreadAreasDemo {    // The method names on the current thread's JVM stack, top first.    static List<String> myFrames() {        return StackWalker.getInstance()                .walk(frames -> frames                        .filter(f -> f.getClassName().equals("ThreadAreasDemo"))                        .map(StackWalker.StackFrame::getMethodName)                        .toList());    }
    static void checkAttendance() {        String who = Thread.currentThread().getName();        System.out.println(who + " stack: " + myFrames());    }
    static void markAttendance() {        checkAttendance();    }
    public static void main(String[] args) throws InterruptedException {        markAttendance();
        Thread helper = new Thread(ThreadAreasDemo::checkAttendance, "helper");        helper.start();        helper.join();    }}
Output
main stack: [myFrames, checkAttendance, markAttendance, main]
helper stack: [myFrames, checkAttendance]

What this code does

  • StackWalker (Java 9) reads the frames on the current thread's JVM stack, top first. The filter keeps only this class's methods, so JDK helper frames do not change the output between Java versions.
  • The main thread's stack holds four frames because main called markAttendance, which called checkAttendance. The helper thread started fresh, so its stack has only the frames of its own calls.

The program counter (pc register) remembers which bytecode instruction this thread runs next. The native method stack is used while the thread runs native methods, which are written in C or C++ inside the JDK.

No other thread can see these areas. That is why two threads can run the same method at the same time without mixing up their local variables. The JVM specification allows these to be separate, but HotSpot uses one stack per thread for both Java frames and native frames. It is the thread's own stack in native memory.

Memory outside the heap: code cache, thread stacks, direct buffers

Native memory is memory the JVM takes from the operating system outside the Java heap. Besides Metaspace, HotSpot keeps three big things there, described after the examples.

Example 3 · Asking the JVM for its memory pools

MemoryPoolsDemo.javaJava
import java.lang.management.BufferPoolMXBean;import java.lang.management.ManagementFactory;import java.lang.management.MemoryPoolMXBean;import java.nio.ByteBuffer;
public class MemoryPoolsDemo {    public static void main(String[] args) {        System.out.println("Memory pools of this JVM:");        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {            long usedKb = pool.getUsage().getUsed() / 1024;            System.out.println("  " + pool.getType() + "  " + pool.getName() + ": " + usedKb + " KB used");        }
        // 4 MB of memory outside the Java heap        ByteBuffer photo = ByteBuffer.allocateDirect(4 * 1024 * 1024);        System.out.println("Direct buffer? " + photo.isDirect());
        for (BufferPoolMXBean pool : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {            System.out.println("  buffer pool '" + pool.getName() + "': "                    + pool.getMemoryUsed() / 1024 + " KB");        }    }}
Sample output
Memory pools of this JVM:
  Non-heap memory  CodeHeap 'non-nmethods': 1250 KB used
  Non-heap memory  Metaspace: 719 KB used
  Non-heap memory  CodeHeap 'profiled nmethods': 312 KB used
  Non-heap memory  Compressed Class Space: 69 KB used
  Heap memory  G1 Eden Space: 2048 KB used
  Heap memory  G1 Old Gen: 0 KB used
  Heap memory  G1 Survivor Space: 0 KB used
  Non-heap memory  CodeHeap 'non-profiled nmethods': 92 KB used
Direct buffer? true
  buffer pool 'mapped': 0 KB
  buffer pool 'direct': 4096 KB
  buffer pool 'mapped - 'non-volatile memory'': 0 KB

What this code does

  • This run is from HotSpot on Java 21 with the default G1 collector. The three CodeHeap pools are the code cache; Metaspace and Compressed Class Space hold class data. Your sizes, and even the pool names with another collector, will differ.
  • The heap pools (Eden, Old Gen, Survivor) are the parts of the heap that the Garbage Collection Basics module explains.
  • The 4 MB direct buffer is counted in the direct buffer pool, not in any heap pool: it lives in native memory.

Example 4 · The whole memory map with jcmd

Terminal
# Terminal 1: start a long-running program with tracking turned onjava -XX:NativeMemoryTracking=summary ExamServer# Terminal 2: find its process id with jps, then ask for the summaryjpsjcmd <pid> VM.native_memory summary scale=MB
Sample output
<pid>:

Native Memory Tracking:

(Omitting categories weighting less than 1MB)

Total: reserved=3340MB, committed=199MB
...
-                 Java Heap (reserved=1882MB, committed=118MB)
...
-                     Class (reserved=1024MB, committed=0MB)
                            (classes #598)
...
-                    Thread (reserved=18MB, committed=1MB)
                            (threads #18)
                            (stack: reserved=18MB, committed=1MB, peak=1MB)
...
-                      Code (reserved=242MB, committed=7MB)
...
-                        GC (reserved=90MB, committed=56MB)
...
-                 Metaspace (reserved=64MB, committed=0MB)
...

What this code does

  • -XX:NativeMemoryTracking=summary makes HotSpot count its own native memory, and jcmd <pid> VM.native_memory prints the totals. This run is trimmed (the ... lines) and comes from Java 21 on 64-bit Windows; your numbers will differ.
  • Reserved is address space set aside; committed is memory actually in use. The heap could grow to 1882 MB but only 118 MB was committed. The 18 threads reserved 18 MB of stack between them, about 1 MB each, but only about 1 MB in total was really used.
  • Class and Metaspace are class data, Code is the code cache, Thread is the thread stacks: every box of the map shows up as a line.
  • Code cache: the machine code made by the JIT compiler. On Java 17 and 21 with tiered compilation, its default maximum is 240 MB (-XX:ReservedCodeCacheSize).
  • Thread stacks: one per thread. On 64-bit Windows and Linux each one reserves 1 MB by default, but only the part actually used is backed by real RAM.
  • Direct buffers: memory from ByteBuffer.allocateDirect, used for fast file and network work. Their limit, -XX:MaxDirectMemorySize, equals the maximum heap size unless you set it.

The garbage collector also needs memory for its own records. So a program started with -Xmx512m (a 512 MB heap) can show well over 512 MB in Task Manager.

A simplified map of JVM memory

Here is the picture this whole section uses. It is simplified: real JVMs have smaller extra areas, and the heap itself is divided into parts that the Garbage Collection Basics module explains.

Example 5 · The memory map in one picture

Text
JVM process (simplified picture, HotSpot)+-----------------------------------+   +-----------------------------+| SHARED BY ALL THREADS             |   | ONE SET PER THREAD          ||                                   |   |                             ||  Heap: objects, arrays,           |   |  JVM stack: one frame for   ||        String pool, static values |   |    each method still running||                                   |   |  Program counter (pc)       ||  Metaspace: class metadata        |   |  Native method stack        ||    (native memory)                |   |  (HotSpot: one shared stack)|+-----------------------------------+   +-----------------------------+Other native memory: code cache (JIT code), GC data, direct buffers
In short
Shared: heap and Metaspace.
Per thread: JVM stack, program counter, native method stack.
Not limited by -Xmx: everything except the heap.

What this code does

  • Objects and arrays always go in the heap box. Local variables and the working values of a call go in a frame in the right box.
  • HotSpot keeps class data in Metaspace, which is native memory. Static values and pooled strings sit on the heap, so they are drawn in the heap line.
  • Left box: one copy for the whole JVM, shared by every thread.
  • Right box: one copy per thread, private to that thread.
  • Everything except the heap is native memory, so -Xmx does not limit it.
  • Each later lesson zooms into one box: frames, heap versus stack, thread stacks, Metaspace and the errors each area can raise.

Next step

Check your understanding

12 quick questions