JVM interview questions
Memory areas, garbage collection, class loading, the JIT and production troubleshooting, the JVM questions asked in mid and senior interviews.
JVM questions test whether you can reason about memory and performance, which matters when production misbehaves. Answer with the concept, then how you'd investigate a real problem.
01Must-know answers
1. Explain the JVM architecture. The class loader subsystem; runtime data areas (heap and metaspace shared, plus a stack, PC register and native stack per thread); and the execution engine (interpreter, JIT, GC), with JNI for native code. (10.1)
2. Stack vs heap?
The stack is per thread: frames, local primitives and references, freed when a method returns. The heap is shared: all objects, managed by the GC. Too deep a stack gives StackOverflowError; a full heap gives OutOfMemoryError. (10.2)
3. What replaced PermGen? Metaspace (Java 8), in native memory, growing by default. (10.2)
4. How does class loading work? Loading, linking (verify, prepare, resolve) and initialisation, lazily on first active use. Bootstrap → platform → application loaders with parent delegation. (10.3)
5. ClassNotFoundException vs NoClassDefFoundError?
A failed dynamic lookup by name, vs a class that was present at compile time but is missing, or failed to initialise, at run time. (10.3)
6. How does garbage collection decide what to free? Reachability from GC roots (thread stacks, static fields, active threads, JNI references). Cycles are collected; there's no reference counting. (10.4)
7. Why is the heap generational? Most objects die young, so frequent cheap minor GCs of the young generation reclaim most garbage; survivors are promoted to the old generation. (10.4)
8. G1 vs ZGC vs Parallel? G1 is the balanced default with region-based, pause-time targets. ZGC is mostly concurrent, with sub-millisecond pauses on large heaps. Parallel maximises throughput for batch work. (10.5)
9. What does the JIT do? It compiles hot bytecode to optimised native code at run time (tiered C1 and C2): inlining, escape analysis, loop optimisations. That's why Java warms up. (10.6)
10. Can Java leak memory? How do you find a leak? Yes, through objects that stay reachable: static caches, listeners, ThreadLocals, unclosed resources. Watch the heap after full GC, take a heap dump, analyse it in Eclipse MAT, and follow the path to the GC root. (10.7)
11. Which JVM options do you use most?
-Xms and -Xmx (heap), -XX:MaxRAMPercentage (containers), -XX:+UseG1GC or -XX:+UseZGC, -Xlog:gc* (GC logs), -XX:+HeapDumpOnOutOfMemoryError, -Xss (stack size).
Loading the rest of the lesson…