Working with Memory Management
1. Understanding Heap and Stack
| Region | Stores |
|---|---|
| Stack | Method frames, local primitives, references |
| Heap | Objects, arrays |
| Metaspace | Class metadata |
| Code cache | JIT-compiled code |
| Direct memory | NIO buffers (off-heap) |
2. Understanding Garbage Collection
| Concept | Detail |
|---|---|
| Reachability | From GC roots — unreachable = collectible |
| Generations | Young (eden + survivor), Old |
| Minor GC | Young gen only |
| Major/Full GC | Whole heap |
3. Using Different Garbage Collectors
| GC | Use Case |
|---|---|
| G1 (default) | General; balances throughput & pauses |
| ZGC | Sub-millisecond pauses, huge heaps |
| Shenandoah | Low-pause concurrent compaction |
| Parallel | Throughput-focused |
| Serial | Single-threaded, small apps |
| Generational ZGC JAVA 21+ | Best of low-pause + generational |
4. Tuning Heap Size
| Flag | Detail |
|---|---|
-Xms | Initial heap size |
-Xmx | Max heap size |
-Xss | Per-thread stack size |
-XX:MaxMetaspaceSize= | Metaspace cap |
| Container-aware | Java 10+ uses cgroup limits |
5. Understanding Generational GC
| Generation | Behavior |
|---|---|
| Young | Most objects die young; cheap to collect |
| Old (tenured) | Long-lived; collected less often |
| Promotion | Survives N collections → moves to old |
6. Using G1 Garbage Collector
| Flag | Detail |
|---|---|
-XX:+UseG1GC | Enable (default since Java 9) |
-XX:MaxGCPauseMillis=200 | Target pause |
-XX:G1HeapRegionSize= | Region size (1-32MB) |
7. Using ZGC
| Flag | Detail |
|---|---|
-XX:+UseZGC | Enable |
-XX:+ZGenerational JAVA 21+ | Generational mode |
| Pauses | Sub-millisecond, regardless of heap size |
| Heaps | Up to 16TB |
8. Monitoring Memory Usage
| Tool | Use |
|---|---|
jstat -gc | GC statistics |
jcmd PID GC.heap_info | Heap snapshot |
jvisualvm / JMC | GUI monitoring |
Runtime.getRuntime().freeMemory() | Programmatic |
9. Detecting Memory Leaks
| Symptom | Cause |
|---|---|
| Old gen grows over time | Object retention leak |
| OutOfMemoryError | Heap exhausted |
| Common causes | Static collections, unclosed resources, ThreadLocal, listener leaks |
| Tools | Heap dump (jcmd PID GC.heap_dump) + Eclipse MAT |
10. Using Weak References
| Type | Strength |
|---|---|
StrongReference | Default; never collected while reachable |
SoftReference | Cleared when memory tight; good for caches |
WeakReference | Cleared at next GC |
PhantomReference | Notified after finalization (cleanup) |
11. Understanding finalize() Method
| Aspect | Detail |
|---|---|
| Status | Deprecated since Java 9, removal-marked Java 18 |
| Replacement | java.lang.ref.Cleaner |
12. Using Cleaner Class
Example: Cleaner
private static final Cleaner CLEANER = Cleaner.create();
public class Resource implements AutoCloseable {
private final Cleaner.Cleanable cleanable;
public Resource() {
State state = new State(); // must NOT capture 'this'
this.cleanable = CLEANER.register(this, state);
}
public void close() { cleanable.clean(); }
static class State implements Runnable {
public void run() { /* free native resources */ }
}
}
| Aspect | Detail |
|---|---|
| Safer than finalize | Runs in dedicated thread |
| Critical rule | State object must not reference owning instance (would prevent collection) |
13. Best Practices for Memory
| Practice | Reason |
|---|---|
| Use try-with-resources | Free resources promptly |
| Limit static collections | Live for JVM lifetime |
| Size collections | Reduce resize overhead |
| Profile before optimizing | Avoid premature tuning |
| Right-size heap | Too small = thrashing; too big = long pauses |