Mid-level (2-5 years)Java

How does JVM memory management and garbage collection work in Java?

Quick answer

The JVM divides memory into a per-thread stack, a shared heap (split into young and old generations) and Metaspace; the garbage collector frees heap objects that are no longer reachable, collecting short-lived young objects frequently and old objects less often.

Each thread has its own stack holding method frames with local variables and references. All objects live on the heap. New objects are allocated in the young generation (Eden and two survivor spaces); objects that survive several minor collections are promoted to the old generation. Class metadata lives in Metaspace, which replaced PermGen in Java 8.

An object is garbage when it can no longer be reached from a GC root such as a thread stack, static field or JNI reference. G1 is the default collector since Java 9 and balances throughput with pause times; ZGC and Shenandoah target very low pauses on large heaps. Typical production problems are OutOfMemoryError from leaks (static collections, listeners, ThreadLocals not cleared) and long pauses from undersized or oversized heaps. Diagnose them with GC logs, heap dumps and tools such as VisualVM or Eclipse MAT.

Key points

  • Stack per thread, heap shared, Metaspace for class data
  • Generational collection: young then old
  • Leaks are objects still reachable by mistake

Questions interviewers ask next

  • What is a memory leak in Java and how do you find one?
  • What is the difference between G1 and ZGC?