Working with Memory Management

1. Understanding Heap and Stack

RegionStores
StackMethod frames, local primitives, references
HeapObjects, arrays
MetaspaceClass metadata
Code cacheJIT-compiled code
Direct memoryNIO buffers (off-heap)

2. Understanding Garbage Collection

ConceptDetail
ReachabilityFrom GC roots — unreachable = collectible
GenerationsYoung (eden + survivor), Old
Minor GCYoung gen only
Major/Full GCWhole heap

3. Using Different Garbage Collectors

GCUse Case
G1 (default)General; balances throughput & pauses
ZGCSub-millisecond pauses, huge heaps
ShenandoahLow-pause concurrent compaction
ParallelThroughput-focused
SerialSingle-threaded, small apps
Generational ZGC JAVA 21+Best of low-pause + generational

4. Tuning Heap Size

FlagDetail
-XmsInitial heap size
-XmxMax heap size
-XssPer-thread stack size
-XX:MaxMetaspaceSize=Metaspace cap
Container-awareJava 10+ uses cgroup limits

5. Understanding Generational GC

GenerationBehavior
YoungMost objects die young; cheap to collect
Old (tenured)Long-lived; collected less often
PromotionSurvives N collections → moves to old

6. Using G1 Garbage Collector

FlagDetail
-XX:+UseG1GCEnable (default since Java 9)
-XX:MaxGCPauseMillis=200Target pause
-XX:G1HeapRegionSize=Region size (1-32MB)

7. Using ZGC

FlagDetail
-XX:+UseZGCEnable
-XX:+ZGenerational JAVA 21+Generational mode
PausesSub-millisecond, regardless of heap size
HeapsUp to 16TB

8. Monitoring Memory Usage

ToolUse
jstat -gcGC statistics
jcmd PID GC.heap_infoHeap snapshot
jvisualvm / JMCGUI monitoring
Runtime.getRuntime().freeMemory()Programmatic

9. Detecting Memory Leaks

SymptomCause
Old gen grows over timeObject retention leak
OutOfMemoryErrorHeap exhausted
Common causesStatic collections, unclosed resources, ThreadLocal, listener leaks
ToolsHeap dump (jcmd PID GC.heap_dump) + Eclipse MAT

10. Using Weak References

TypeStrength
StrongReferenceDefault; never collected while reachable
SoftReferenceCleared when memory tight; good for caches
WeakReferenceCleared at next GC
PhantomReferenceNotified after finalization (cleanup)

11. Understanding finalize() Method

AspectDetail
StatusDeprecated since Java 9, removal-marked Java 18
Replacementjava.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 */ }
    }
}
AspectDetail
Safer than finalizeRuns in dedicated thread
Critical ruleState object must not reference owning instance (would prevent collection)

13. Best Practices for Memory

PracticeReason
Use try-with-resourcesFree resources promptly
Limit static collectionsLive for JVM lifetime
Size collectionsReduce resize overhead
Profile before optimizingAvoid premature tuning
Right-size heapToo small = thrashing; too big = long pauses