Skip to the page

JVM, memory and Java versions · core

Heap, stack, Metaspace and garbage collection

Objects live in the heap, frames in thread stacks and class data in Metaspace. The collector frees objects that cannot be reached from GC roots. Humongous objects in G1 cause long pauses.

The notes

What you must know

  • Stack: one per thread; frames hold local primitives and references. Size set by -Xss. Very deep recursion gives StackOverflowError.
  • Heap: every object and array, including the string pool. Shared by all threads, cleaned by the GC, sized by -Xmx. When full: OutOfMemoryError: Java heap space.
  • Metaspace (Java 8+, replaced PermGen): class metadata in native memory, unlimited unless -XX:MaxMetaspaceSize is set. Class-loader leaks fill it.
  • Other native memory: thread stacks, JIT code cache, direct ByteBuffers, GC bookkeeping. The process always uses more than the heap.
  • The GC uses reachability, not reference counting. Roots: locals in running frames, static fields, live threads, JNI references.
  • Generational idea: most objects die young. New objects go to eden; a young collection copies survivors. The old generation is collected less often. A full GC compacts everything and is expensive.
  • Stop-the-world pauses stop application threads; concurrent phases run alongside. System.gc() is only a request and usually hurts. Reference types: soft, weak, phantom.
  • G1 is the default on most machines. ZGC does almost all work concurrently with very short pauses. Parallel gives high throughput with longer pauses (batch jobs). Serial is for tiny heaps. Shenandoah is concurrent too. G1 humongous objects (half a region or more) go straight to old regions. Many of them fragment the heap and cause long pauses. Stream big exports instead of building one byte array; raise -XX:G1HeapRegionSize as a stop-gap. Decide with data: GC logs (-Xlog:gc*:file=gc.log), pause percentiles and a load test before and after.

The red pen

Common traps: mistake → fix

  • Mistake: Java uses reference counting

    Fix: it uses reachability from GC roots.

  • Mistake: System.gc() is a good way to free memory

    Fix: it is a request and often causes long pauses.

  • Mistake: A bigger heap always fixes slow GC

    Fix: large objects and allocation habits can still cause long pauses.

Easy to hard

Questions interviewers ask, easy to hard

  1. Where do objects, local variables and class data live?
  2. What error do you get when each one runs out?
  3. How does the garbage collector decide what to delete?
  4. Which collector for a payments API with a strict p99, and which for a nightly batch?
  5. Why can an export feature cause GC pauses of several seconds?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview