Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 77 ยท Java Interview Questions

Java: JVM, Memory Model and Garbage Collection

Answer Java interview questions on heap vs stack, garbage collection generations, class loading, volatile and happens-before, with a mark-and-sweep model.

Senior Java interviews move from the language to the runtime: where objects live, how garbage collection decides what to free, how classes get loaded, and what volatile guarantees between threads. You do not need to tune a collector in an interview. You need a clear mental model and the right vocabulary.

All real JVM behavior here is described in read-only text and code. The runnable examples are small JavaScript stand-ins that model the ideas (reachability, generations, visibility) and say what they simplify. For full tutorials see JVM Architecture, Memory and Garbage Collection and JVM Tuning Flags.

Where things live

Stack One per thread. Frames, locals, references.
Heap Shared. All objects and arrays.
Metaspace Class metadata, in native memory.

References on the stack point to objects on the heap.

1 / 2

Stack versus heap

Q: What is the difference between the stack and the heap? Each thread has its own stack made of frames: one per method call, holding local variables (primitives and references) and the operand stack. A frame disappears when the method returns. The heap is shared by all threads and holds every object and array. The garbage collector manages the heap; you never free memory yourself.

Java
void demo() {
    int count = 3;                       // primitive: lives in the stack frame
    StringBuilder sb = new StringBuilder(); // reference on the stack,
                                            // object on the heap
}

Two errors to know: StackOverflowError (too-deep recursion exhausts a thread's stack) and OutOfMemoryError (the heap, or another region such as metaspace, is full even after collection). Escape analysis may let the JIT avoid allocating a heap object that never escapes a method, so "objects always live on the heap" is the model, not a promise about every optimization.

Garbage collection: reachability

Q: How does the JVM decide an object is garbage? By reachability, not reference counting. Starting from GC roots (local variables on thread stacks, static fields, JNI references and a few others), the collector follows references. Everything it reaches is live. Everything else is garbage, even if objects point at each other in a cycle.

Mark and sweep, the classic idea: mark all reachable objects, then sweep (reclaim) the rest. Real collectors also compact or copy survivors to avoid fragmentation.

JS Stand-in: mark and sweep on an object graph

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cycle a and b is freed in the first pass. A reference-counting scheme would leak it, which is why Java does not use one.

Generations

Q: What are GC generations, and why do they exist? The weak generational hypothesis says most objects die young. So the heap is split: new objects go to the young generation (Eden plus two survivor spaces) and are collected often and cheaply by a minor GC. Objects that survive several collections are promoted to the old generation, collected less often by a more expensive major or mixed collection. Collecting only the small young area is fast, which keeps pauses short.

JS Stand-in: young generation, survivors and promotion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Q: Name some collectors. Serial (single thread, tiny heaps), Parallel (throughput), G1 (the default on modern JVMs, region-based, aims at pause-time goals), ZGC and Shenandoah (very low pauses, mostly concurrent). Say what trade-off each makes, and leave exact flags to the docs. A stop-the-world pause is when application threads are halted so the collector can work.

Q: Can you force garbage collection? System.gc() is only a request, and the JVM may ignore it. Do not rely on it. Memory leaks in Java are almost always objects that are still reachable by mistake: static collections that only grow, listeners never removed, ThreadLocal values on pooled threads, caches without eviction.

Class loading

Q: How are classes loaded? Lazily, the first time a class is needed. Three steps:

  1. Loading: a class loader finds the bytes and creates a Class object.
  2. Linking: verify the bytecode, prepare static fields with default values, resolve references.
  3. Initialization: run static initializers and assign static fields, once.

Loaders form a hierarchy with parent delegation: a loader first asks its parent, so core classes such as java.lang.String always come from the bootstrap loader and cannot be replaced by an application class of the same name. Typical layers: bootstrap, platform, and application (system) loader. Frameworks add custom loaders, and the same class loaded by two loaders counts as two different types.

Java
System.out.println(String.class.getClassLoader());              // null (bootstrap)
System.out.println(Main.class.getClassLoader());                // application loader

volatile and happens-before

Q: What does volatile do? It gives a field two guarantees: visibility (a write is seen by later reads in other threads) and ordering (the write is not reordered with earlier operations as seen by a thread that reads it). It does not make compound actions atomic: count++ on a volatile field is still read, add, write.

The Java Memory Model describes this with happens-before edges. If action A happens-before action B, then A's effects are visible to B. Key edges:

  • Program order within one thread.
  • A write to a volatile field happens-before every later read of that field.
  • Releasing a monitor (leaving synchronized) happens-before the next acquisition of the same monitor.
  • Thread.start() happens-before everything in the started thread; everything in a thread happens-before another thread's successful join() on it.
Java
class Worker {
    private volatile boolean running = true;   // visibility flag
    void stop() { running = false; }
    void loop() { while (running) { /* work */ } }
}

Without volatile, the loop thread may keep using a cached true forever, because nothing forces visibility.

JS Stand-in: why a plain flag may never be seen

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is a deliberately crude picture. Real CPUs and the JIT cause the effect through caches, store buffers and reordering, and without volatile the outcome is unspecified, not "always stale".

Q: When is volatile not enough? For read-modify-write (i++), for invariants spanning several fields, and for check-then-act. Use synchronized, java.util.concurrent.atomic (such as AtomicInteger) or locks. The next lesson covers those in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do objects live in the JVM?

    Objects and arrays are heap allocated. Stack frames hold primitives and references.
  2. 2. An object a and an object b reference each other, and nothing else references either. What happens in a tracing garbage collector?

    Collection is based on reachability from roots, so cycles do not keep objects alive.
  3. 3. Why is the heap split into young and old generations?

    The weak generational hypothesis: frequent, quick minor collections handle most garbage.
  4. 4. What is true about volatile int counter and counter++ from many threads?

    volatile gives visibility and ordering, not atomic read-modify-write. Use AtomicInteger or a lock.
  5. 5. What does parent delegation in class loading ensure?

    A loader asks its parent first, so trusted core classes win.

Summary

  • Stacks are per thread and hold frames; the heap is shared and holds objects.
  • The GC marks everything reachable from roots and reclaims the rest; cycles are not a problem.
  • Generations exploit "most objects die young": frequent minor collections, rare major ones.
  • Classes load lazily (load, link, initialize) with parent delegation.
  • volatile gives visibility and ordering, not atomicity; happens-before edges define what a thread can see.

Next: Java: Concurrency, Streams and Modern Java.