Understanding JVM Memory Management

1. Understanding Memory Areas

AreaPurpose
HeapObjects, arrays
MetaspaceClass metadata (off-heap, since Java 8)
StackPer-thread frames, locals
PC RegisterPer-thread instruction pointer
Native Method StackJNI frames
Code CacheJIT-compiled native code
Direct buffersOff-heap NIO memory

2. Understanding Heap Structure

Heap Layout (Generational GC)

+----------------------- Heap -----------------------+
| Young Gen                  | Old Gen (Tenured)     |
|  Eden | Survivor 0 | S 1   |  long-lived objects   |
+----------------------------+-----------------------+
RegionUse
EdenNew allocations
Survivor 0/1Survived 1+ minor GC
Old GenPromoted long-lived

3. Understanding Young Generation

AspectDetail
Minor GCCollects Young only — fast (copying)
Survivor copyEden+S0 → S1 (or vice versa)
Tenuring threshold-XX:MaxTenuringThreshold

4. Understanding Object Allocation (TLAB)

ConceptDetail
TLABThread-Local Allocation Buffer in Eden
Bump pointerO(1) allocation, no contention
ResizeAdaptive (-XX:+ResizeTLAB)
Slow pathRefill or allocate in shared Eden

5. Understanding Object Promotion

TriggerDetail
Age thresholdSurvived N copy cycles
Survivor fullPromote early
Premature promotionBad for GC pause times

6. Using Memory Flags (-Xms, -Xmx, -XX:MetaspaceSize)

FlagUse
-XmsInitial heap
-XmxMax heap
-XssStack size per thread
-XX:MetaspaceSizeInitial metaspace
-XX:MaxMetaspaceSizeCap metaspace
-XX:MaxDirectMemorySizeDirect ByteBuffer cap

7. Understanding Escape Analysis

ResultOptimization
No escapeScalar replacement / stack allocation
Method-only escapeLock elision
Global escapeNo optimization
Flag-XX:+DoEscapeAnalysis (default on)

8. Understanding Native Memory (off-heap)

SourceDetail
DirectByteBufferNIO; counts against MaxDirectMemorySize
Foreign Memory APIJava 22+ replacement for Unsafe
JNI mallocsOutside JVM accounting
TrackingNative Memory Tracking (-XX:NativeMemoryTracking=summary)

9. Understanding String Interning

AspectDetail
StorageString table in main heap (Java 7+)
str.intern()Returns canonical instance
Sizing-XX:StringTableSize
Statsjcmd VM.stringtable

10. Using Compressed OOPs (-XX:+UseCompressedOops)

AspectDetail
DefaultOn for heaps ≤ ~32 GB
Effect32-bit refs in 64-bit JVM (3-bit shift)
Disable-XX:-UseCompressedOops for huge heaps
Class pointers-XX:+UseCompressedClassPointers

11. Monitoring Memory Usage

ToolUse
jcmd PID GC.heap_infoQuick heap stats
jstat -gc PID 1sLive GC counters
JMX MemoryMXBeanProgrammatic
JFR / Mission ControlRecording-based

12. Detecting Memory Leaks

Leak-Hunting Workflow

  1. Reproduce growing usage with -Xlog:gc*
  2. Trigger heap dump: jcmd PID GC.heap_dump heap.hprof
  3. Open in Eclipse MAT — check Dominator Tree, Leak Suspects
  4. Identify retained-by chain (often static caches, ThreadLocals)
  5. Patch and verify with regression heap dump
Common CauseFix
Static collectionsUse WeakHashMap or LRU cache
ThreadLocal in poolsAlways remove() on exit
Listeners not unregisteredSymmetric add/remove
ClassLoader leaksCommon in app servers — release on undeploy