Skip to the page

JVM and memory · Concept

Heap, stack and Metaspace

The 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

  1. A method creates a new ArrayList and keeps it in a local variable. What's on the stack and what's on the heap?
  2. What was PermGen, and why was it replaced?
  3. Your pod has a 2 GB limit and -Xmx2g. What goes wrong?
  4. What causes a StackOverflowError in real code?
  5. 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 -Xmx or -XX:MaxRAMPercentage. Full gives OutOfMemoryError: Java heap space.
  • Metaspace (Java 8+, replaced PermGen, JEP 122): class metadata in native memory, unlimited unless -XX:MaxMetaspaceSize is set. Class-loader leaks give OutOfMemoryError: 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 voice

Practise 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.

Start your free interview