Java JVM and memory
Stop guessing about performance and memory. The goal in this topic is a measurement habit, not a set of numbers to recite.
6 concepts · 19 interview questions
What this topic covers
Every concept in jvm and memory, and the questions each one gets asked as. Where a question links, it has a full write-up.
Memory areas
Heap for objects, stack per thread for frames, Metaspace for class metadata — with escape analysis making the heap/stack split less absolute than tutorials claim.
- What lives on the heap and what lives on the stack?
- What replaced PermGen, and why?
- What causes StackOverflowError versus OutOfMemoryError?
Garbage collection
Collection is driven by reachability, not scope. Generational collectors exploit the fact that most objects die young.
- How does garbage collection decide what to collect?
- Which garbage collector should you use, and how would you decide?
- What is a stop-the-world pause?
- Does calling System.gc() do anything?
Memory leaks
In a managed language a leak is unwanted reachability — static collections, listeners, ThreadLocals and ClassLoaders.
- How do you get a memory leak in a garbage-collected language?
- How do you find a leak from a heap dump?
- What are strong, soft, weak and phantom references for?
Class loading
Loading, linking and initialisation, delegated up a parent chain. Static initialisers run once, at a point people rarely predict.
- What happens when a class is loaded?
- When exactly does a static initialiser run?
- What is a ClassLoader leak?
JIT compilation
Interpretation, then C1, then C2, with inlining and deoptimisation — which is why the first measurement of anything is a lie.
- What does the JIT compiler do?
- Why is your first benchmark result wrong?
- What is warm-up, and how long does it take?
Profiling and diagnostics
JFR, jcmd, jmap and thread dumps. Learning these before an incident is the difference between diagnosis and guessing.
- How do you diagnose high CPU in a running JVM?
- How do you read a thread dump?
- How do you benchmark Java code correctly?