Top 10 Must‑Ask JVM Interview Questions
This article presents ten essential JVM interview questions, covering the Java 8 memory model, object allocation flow, common GC algorithms and collectors, class‑loading mechanics, OOM and CPU‑spike troubleshooting, tuning parameters, and the differences among strong, soft, weak and phantom references.
1. JVM Memory Model (Java 8)
Java 8 replaces the permanent generation (PermGen) with Metaspace, which resides in native memory and has no fixed size limit. The runtime memory is divided into:
Heap – contains the Young Generation (Eden, Survivor 0, Survivor 1) and the Old Generation.
Non‑Heap – includes Metaspace (class metadata) and per‑thread stacks/PC/native stacks.
Key areas :
Eden – stores newly created objects that are typically short‑lived.
Survivor 0/1 – act as buffers for objects that survive Minor GCs, reducing promotion to the Old Generation.
Old Generation – holds long‑lived or large objects; triggers Major GCs.
Metaspace – stores class metadata in native memory; size grows on demand.
2. Object Allocation and Flow
New object → Eden
├── Large object (size > -XX:PretenureSizeThreshold) → Old Generation
▼
Minor GC (collect Eden)
├── Surviving objects → Survivor 0
▼
Next Minor GC (collect Eden + Survivor 0 → Survivor 1)
├── Age +1
▼
When age reaches threshold (default 15) → promotion to Old GenerationThe two Survivor spaces provide a copying buffer that minimizes object promotion and avoids fragmentation in the Old Generation.
3. Common GC Algorithms
Mark‑Sweep – marks live objects then clears unmarked ones; used for the Old Generation; can cause memory fragmentation.
Copying – copies live objects to another region; used for the Young Generation; results in ~50% memory utilization.
Mark‑Compact – marks live objects and compacts them to one end; used for the Old Generation; incurs higher moving cost.
4. GC Collectors
Serial (young) – single‑threaded copying collector; enabled with -XX:+UseSerialGC.
ParNew (young) – multithreaded version of Serial; enabled with -XX:+UseParNewGC.
Parallel Scavenge (young) – throughput‑oriented parallel copying; enabled with -XX:+UseParallelGC.
Serial Old (old) – serial mark‑compact paired with Serial; enabled with -XX:+UseSerialOldGC.
Parallel Old (old) – parallel mark‑compact for the Old Generation; enabled with -XX:+UseParallelOldGC.
CMS (old) – low‑latency concurrent collector (deprecated); enabled with -XX:+UseConcMarkSweepGC. Six phases: initial mark, concurrent mark, pre‑clean, remark, concurrent sweep, concurrent reset.
G1 (global) – region‑based collector with predictable pauses; default from JDK 9; enabled with -XX:+UseG1GC. Prioritises regions with the most garbage.
ZGC (global) – sub‑millisecond pause collector; available from JDK 11; enabled with -XX:+UseZGC.
5. Class Loading Mechanism & Parent‑Delegation Model
Loading proceeds through five phases:
Loading → Verification → Preparation → Resolution → InitializationParent‑delegation hierarchy:
BootstrapClassLoader (loads rt.jar)
↓
ExtensionClassLoader (loads $JAVA_HOME/jre/lib/ext)
↓
ApplicationClassLoader (loads classpath)A child loader first delegates to its parent; only if the parent cannot find the class does the child attempt to load it. This prevents duplicate class loading and protects core APIs.
6. OOM Scenarios and Investigation
Heap OOM – objects cannot be reclaimed (memory leak). Diagnose with jmap and Eclipse MAT.
Metaspace OOM – too many loaded classes (e.g., dynamic proxies). Diagnose with jmap -clstats.
Stack OOM – deep recursion.
Direct Memory OOM – improper NIO usage; diagnose with jcmd.
Typical investigation steps:
# 1. View GC usage
jstat -gcutil <PID> 1000
# 2. Export heap dump
jmap -dump:format=b,file=heap.hprof <PID>
# 3. Analyse with MAT (Leak Suspects → Dominator Tree)
# 4. Real‑time inspection (Arthas)
java -jar arthas-boot.jar
thread -n 3Enable automatic heap dumps on OOM:
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/path/heap.hprof7. CPU‑Spike Investigation
# Identify high‑CPU process
top -c
# Find high‑CPU thread ID
top -Hp <PID>
# Convert TID to hex
printf "%x
" <TID>
# Locate stack frame
jstack <PID> | grep '0x<hex>' -A 20
# Analyse the stack to pinpoint the codeCommon causes include infinite loops, spin‑wait (CAS retries), regex backtracking, and excessive logging.
8. Memory‑Leak Investigation
Symptoms: memory does not drop after GC, Old Generation usage > 90 %, frequent Full GCs, eventual OOM.
Typical leak sources: un‑cleared collections, lingering ThreadLocal entries, undeleted listeners, unclosed streams, static collections holding objects.
# 1. Confirm leak
jstat -gcutil <PID> 1000
# 2. Export heap dump
jmap -dump:format=b,file=heap.hprof <PID>
# 3. Analyse with MAT (Leak Suspects → Dominator Tree → GC Roots)MAT’s Leak Suspects and Dominator Tree help locate the leaking objects and the GC roots path.
9. Common JVM Tuning Parameters
Memory‑related flags :
-Xms4g -Xmx4g # Initial / max heap size
-Xmn2g # Young generation size
-XX:MetaspaceSize=256m # Initial Metaspace
-XX:MaxMetaspaceSize=512m # Max Metaspace
-XX:SurvivorRatio=8 # Eden:Survivor = 8:1
-XX:NewRatio=2 # Old:Young = 2:1GC‑related flags :
-XX:+UseG1GC # Enable G1 (default from JDK 9)
-XX:MaxGCPauseMillis=100 # Target pause time
-XX:G1NewSizePercent=5 # Initial young‑gen proportion
-XX:InitiatingHeapOccupancyPercent=45 # Mixed GC trigger
-XX:+UseZGC # Enable ZGC (JDK 11+)
-XX:ConcGCThreads=4 # Number of concurrent GC threadsDiagnostic flags :
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/path/heap.hprof
-Xloggc:gc.log
-XX:+PrintGCDetails10. Reference Types
Strong Reference – never reclaimed. Example: Object o = new Object(); Soft Reference – reclaimed only when memory is low; suitable for caches. Example: SoftReference<T> ref; Weak Reference – reclaimed on the next GC; used for ThreadLocal keys. Example: WeakReference<T> ref; Phantom Reference – enqueued after finalization; cannot retrieve the referent. Example: PhantomReference<T> ref; Understanding these reference types helps design memory‑efficient structures and avoid leaks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
