Tech Interview RoomStudy guides

Advanced Java

Describe the JVM memory areas and the class-loading process.

Advanced · 2 min read · Lesson 7 of 10 in Advanced Java

Runtime data areas

  • Heap (shared): all objects and arrays. Generational collectors split it into young generation (Eden plus two survivor spaces) and old generation. Size with -Xms/-Xmx or, in containers, -XX:MaxRAMPercentage.
  • Metaspace (native memory since Java 8, replacing PermGen): class metadata, method bytecode, constant pools. Unbounded by default; cap with -XX:MaxMetaspaceSize.
  • Thread stacks (per thread): frames with local variables and operand stacks; size with -Xss (default about 1 MB on 64-bit Linux).
  • Code cache: JIT-compiled native code.
  • Direct (off-heap) memory: ByteBuffer.allocateDirect, Netty buffers; capped by -XX:MaxDirectMemorySize.
  • Plus GC data structures, symbol tables and native allocations by libraries.

This is why a container's memory limit must cover much more than -Xmx.

Class loading

  1. Loading: find the bytes and create a Class object.
  2. Linking: verify bytecode, prepare static fields with defaults, resolve symbolic references (often lazily).
  3. Initialisation: run static initialisers, once, thread-safely (this is what the holder-singleton idiom relies on).

Class loaders and delegation

Bootstrap (core JDK) → Platform → Application (classpath). A loader delegates to its parent first, so application code cannot replace java.lang.String. A class's identity is its name plus its loader, which is why the same class loaded by two loaders causes ClassCastException: X cannot be cast to X. Application servers and Spring Boot DevTools use child loaders to isolate or reload application classes.

Follow-up questions interviewers ask

Try answering each one before you open it.

What are the different OutOfMemoryError messages and their causes?
  • Java heap space: live data exceeds -Xmx (a leak or an undersized heap).
  • GC overhead limit exceeded: the JVM spends over 98% of time in GC recovering under 2% of heap.
  • Metaspace: too many classes, often a class-loader leak from redeployments or runtime proxy generation.
  • unable to create native thread: OS thread or memory limits.
  • Direct buffer memory: off-heap buffers exhausted.
  • In containers, the process may instead be OOMKilled by the kernel with no Java error at all, because total native plus heap memory exceeded the cgroup limit.
How does a class-loader leak happen?

A long-lived object outside the web application (a JDK static, a thread, a ThreadLocal on a pooled thread, a JDBC driver registered in DriverManager) holds a reference to a class loaded by the application's loader. That pins the loader and therefore every class it loaded, so each redeploy adds a full copy of the application's classes to Metaspace until it overflows.