JVM Memory Model and Garbage Collection
Memory areas
| Area | Holds | Lifetime |
|---|---|---|
| Stack (per thread) | Method frames, local variables, references | Until the method returns |
| Heap | Objects and arrays | Until unreachable and collected |
| Metaspace | Class metadata | Until the class loader is collected |
| Code cache | JIT-compiled code | JVM lifetime |
void demo() {
int count = 3; // primitive: on the stack
StringBuilder sb = new StringBuilder(); // reference on the stack, object on the heap
process(sb);
} // frame popped; sb becomes unreachable
Garbage collection
An object is eligible for collection when no live reference can reach it from a GC root (thread stacks, static fields, JNI).
| Concept | Meaning |
|---|---|
| Generational hypothesis | Most objects die young |
| Young generation | New objects (eden + survivor spaces); minor GCs are frequent and fast |
| Old generation | Long-lived objects; major/mixed GCs are rarer and costlier |
| Stop-the-world | Application threads paused during parts of GC |
Collectors
| Collector | Goal | Notes |
|---|---|---|
| G1 (default) | Balanced throughput and pauses | Region-based, good general choice |
| ZGC / Shenandoah | Very low pauses on large heaps | Mostly concurrent |
| Parallel | Maximum throughput | Longer pauses |
| Serial | Tiny heaps, single core | Simple |
java -Xms512m -Xmx2g -XX:+UseG1GC -Xlog:gc* -jar app.jar
Common memory problems
| Problem | Cause | Fix |
|---|---|---|
OutOfMemoryError: Java heap space | Heap too small or a leak | Profile with a heap dump; fix retention |
| Memory leak | Objects kept reachable (static maps, listeners, caches without eviction) | Remove references; bounded caches; weak references |
StackOverflowError | Very deep or infinite recursion | Convert to iteration; fix base case |
| Long GC pauses | Large old generation, wrong collector | Tune heap, try ZGC, reduce allocation |
Tools
jcmd,jstat,jmapfor inspecting a running JVM.- Java Flight Recorder and VisualVM / Mission Control for profiling.
- Heap dump analysis with Eclipse MAT.
TIP
Fix allocation hot spots before tuning GC flags. Most performance gains come from creating fewer objects, not from exotic JVM options.