JVM and memory · Concept
Heap, stack and Metaspace
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Where do objects, local variables and class information live in the JVM's memory? What error do you get when each one runs out?
Then
Follow-ups the interviewer asks next
- A method creates a new ArrayList and keeps it in a local variable. What's on the stack and what's on the heap?
- What was PermGen, and why was it replaced?
- Your pod has a 2 GB limit and
-Xmx2g. What goes wrong? - What causes a StackOverflowError in real code?
- What memory does the JVM use besides these three?
The answer
What a strong answer covers
- Stack: one per thread; frames hold local primitives and references. Its size is set by
-Xss(about 1 MB by default on 64-bit Linux). Very deep or endless recursion gives StackOverflowError. - Heap: every object and array, including the string pool (in the heap since Java 7); shared by all threads; cleaned by the GC; sized by
-Xmxor-XX:MaxRAMPercentage. Full givesOutOfMemoryError: Java heap space. - Metaspace (Java 8+, replaced PermGen, JEP 122): class metadata in native memory, unlimited unless
-XX:MaxMetaspaceSizeis set. Class-loader leaks giveOutOfMemoryError: Metaspace. - Other native memory: thread stacks, the JIT's code cache, direct ByteBuffers (Netty), GC bookkeeping, native libraries. The process always uses more than -Xmx, which is why -Xmx equal to the container limit gets the pod killed.
- The JIT can avoid some allocations (escape analysis), but in the language model objects live on the heap.
The red pen
Common traps
Avoid:"objects created in a method live on the stack"; "PermGen still exists"; "the JVM uses exactly -Xmx".
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.