Sub topic 2
The Generational Heap: Eden, Survivor Spaces, and Old Generation
Assume you know basic Java syntax, object references, and how to run Java programs from the command line. The JVM divides the heap by object age because most objects become unreachable quickly.
The generational heap
New objects usually enter eden. When a young collection finds an object still reachable, the JVM copies it to a survivor space. Objects that survive several collections are promoted to the old generation.
This design makes young collections fast because they inspect a smaller region. A large number of long-lived objects can still cause old-generation collections and pauses.
Choosing a collector
The collector controls how the JVM finds and reclaims unreachable objects.
| Collector | Typical choice |
|---|---|
| Serial | Small heaps or simple command-line programs |
| Parallel | Throughput-focused batch applications |
| G1 | General server workloads and predictable pause targets |
| ZGC | Very large heaps with very short pause requirements |
G1 is often a practical default for services. ZGC reduces pause times but can require more CPU and has different operational trade-offs. Measure a real workload before changing the default.
Soft, weak, and phantom references
A strong reference keeps an object alive. A SoftReference may be cleared when memory is scarce, so it can support memory-sensitive caches. A WeakReference does not prevent collection and suits temporary associations. A PhantomReference is used with a ReferenceQueue to observe that an object is ready for cleanup; it cannot retrieve the object.
Metaspace and class metadata
Metaspace stores class metadata outside the Java heap. Loading many classes, especially through repeatedly created class loaders, can exhaust it. The relevant failure may be OutOfMemoryError: Metaspace, even when the Java heap has free space.
Memory leaks in garbage-collected code
Garbage collection removes unreachable objects, not objects that your program accidentally keeps reachable. Common causes include static collections that grow forever, listeners that are never removed, unbounded caches, and ThreadLocal values retained by pooled threads.
Exercise
Why can a static list cause a memory leak?
Show answer
The static field is reachable from a GC root, so every object in the list remains reachable and cannot be collected.