Reading — step 1 of 7
Learn
~1 min readReflection and JVM
The JVM divides memory into a few regions:
- Heap — all
newallocations live here. Subdivided:- Young Generation — Eden + Survivor spaces. New objects start here.
- Old Generation (Tenured) — long-lived objects promoted from Young.
- Metaspace (replaced PermGen in Java 8) — class metadata.
- Stack — one per thread; method frames, local primitives.
- Native heap — JNI allocations, direct ByteBuffers.
Garbage collection lifecycle:
- New object → Eden
- Eden fills → minor GC copies live objects to Survivor space
- Survivors that age out → promoted to Old
- Old fills → major GC (or full GC) — slower, more thorough
Algorithms (set with -XX:+UseG1GC etc.):
- Serial GC — single-threaded, fine for small heaps
- Parallel GC — multi-threaded, throughput-focused
- G1GC — region-based, predictable pause times. Default in modern Java.
- ZGC, Shenandoah — sub-ms pauses, large heaps
Tuning flags:
-Xms256m # initial heap
-Xmx2g # max heap
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200
-Xss512k # thread stack size
Watching GC:
-Xlog:gc* # Java 9+ unified logging
-Xlog:gc*:gc.log # to file
Or at runtime, use jstat, jcmd, or VisualVM/JMC.
Object lifecycle insights:
finalize()is deprecated — never reliable, never used in modern code- Use try-with-resources /
Cleaner(Java 9+) for cleanup - Soft / Weak / Phantom references — for caches and reference-aware structures
Memory leaks in Java are usually:
- Static collections that grow unbounded
- Listeners not unregistered
- ThreadLocals that retain large values
- ClassLoader leaks (web apps that hot-reload)
Tools: VisualVM, YourKit, Eclipse MAT for heap dumps. jmap -dump:live,format=b,file=heap.hprof <pid> to capture, then analyze.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…