Master JVM Memory & GC: 20 Essential Interview Questions Explained

This article provides a comprehensive, interview‑focused guide to the Java Virtual Machine, covering memory regions, garbage‑collection algorithms, reference types, GC roots, STW pauses, OopMap, safe points, stack overflow, class loading, the parent‑delegation model, stack allocation, and object layout, all with clear explanations and diagrams.

JavaEdge
JavaEdge
JavaEdge
Master JVM Memory & GC: 20 Essential Interview Questions Explained

1. JVM Memory Areas

The JVM divides runtime memory into several distinct regions, each with specific responsibilities and lifetimes. The purple area in the diagram represents thread‑shared regions, while other areas are thread‑private.

Program Counter (PC) Register : a thread‑private pointer indicating the current bytecode instruction; its lifecycle matches the thread.

Java Virtual Machine Stack : also known as the thread stack; each frame stores local variables, operand stack, dynamic linking, and return address.

Native Method Stack : supports native (C/C++) method calls.

Heap : the largest, shared memory region where most objects are allocated.

Method Area : shared storage for class metadata, static variables, and the runtime constant pool.

Direct Memory : off‑heap memory used by NIO, often paired with weak references for efficient I/O.

2. How Are Garbage Objects Identified?

Two main strategies are described:

Reference‑Counting Algorithm : each object maintains a counter incremented on each reference and decremented when a reference is cleared. When the count reaches zero, the object is considered garbage. This method is simple and fast but cannot reclaim cyclic references.

Root‑Reachability (GC Roots) Algorithm : the JVM defines a set of root objects (GC Roots). Starting from these roots, the collector traverses reference chains; any object not reachable from a root is reclaimed. This approach handles cycles.

3. What Are GC Roots?

GC Roots consist of fixed and temporary objects:

Fixed GC Roots : objects referenced from the virtual machine stack, static fields, constant pool, JNI handles, internal JVM objects, objects held by synchronized blocks, and JMX/JVMTI callbacks.

Temporary GC Roots : objects that become roots during a partial collection to ensure correctness, especially when a region is being reclaimed.

4. Four Types of Java References

Strong Reference : ordinary references; objects are never reclaimed while a strong reference exists.

Soft Reference :

SoftReference<String> softRef = new SoftReference<String>(str);

cleared only when memory is low.

Weak Reference :

WeakReference<String> weakRef = new WeakReference<String>(str);

cleared on the next GC cycle; used by ThreadLocal to avoid memory leaks.

Phantom Reference : the weakest reference, used mainly for cleanup notifications such as zero‑copy buffer reclamation.

5. Generational Collection Theory

Most collectors assume:

Weak Generation Hypothesis : most objects die young.

Strong Generation Hypothesis : objects that survive many collections become harder to collect.

Thus, young generations are collected frequently, while the old generation is collected less often. A remembered set tracks references from old to young objects to avoid scanning the entire old generation.

6. Garbage‑Collection Algorithms

Three primary families are covered:

Mark‑Sweep : marks reachable objects, then sweeps away the rest. Drawbacks include long pause times and memory fragmentation.

Mark‑Copy : copies live objects to a new space, eliminating fragmentation but requiring twice the memory.

Mark‑Compact : combines marking with compaction, moving live objects together to free contiguous space.

7. What Is STW (Stop‑The‑World)?

During certain GC phases, all Java application threads are paused (except GC helper threads). This global pause ensures a consistent view of the heap.

8. Why Is STW Needed?

Without STW, the mutator could modify object graphs while the collector is identifying reachable objects, leading to incorrect reclamation. STW guarantees that reference relationships remain stable during root enumeration.

9. How Does the Collector Find GC Roots?

The JVM enumerates roots while the world is stopped. To avoid scanning every object, HotSpot records root locations in an OopMap during safe points, enabling fast root lookup.

10. Purpose of OopMap

An OopMap records which stack slots contain object references at each safe point, allowing the collector to enumerate roots without a full stack scan and supporting accurate (precise) GC.

11. What Is a Safe Point?

Safe points are specific locations in the bytecode (e.g., method entry, loop back‑edges, exception handlers) where the JVM can safely pause a thread for GC. Two interruption strategies are used:

Preemptive Interrupt : forces a thread to stop immediately, then resumes it until it reaches a safe point.

Cooperative Interrupt : threads poll a flag and voluntarily pause at the next safe point.

12. Safe Region

A safe region extends the concept of a safe point: a code segment during which reference relationships are guaranteed not to change, allowing the GC to ignore threads that are already inside such a region.

13. Common Garbage Collectors

Serial : single‑threaded, uses copying for the young generation.

ParNew : multithreaded version of Serial for the young generation.

Parallel Scavenge : multithreaded young‑gen collector targeting high throughput; configurable via -XX:MaxGCPauseMillis and -XX:GCTimeRatio.

Serial Old : single‑threaded collector for the old generation, often paired with CMS.

Parallel Old : multithreaded old‑gen collector, works with Parallel Scavenge.

CMS : concurrent collector that performs most work alongside application threads; phases include Initial Mark, Concurrent Mark, Remark, and Concurrent Sweep. Drawbacks: can affect application throughput, generate “floating garbage,” and cause fragmentation.

G1 (Garbage‑First) : divides the heap into equal‑sized regions; collects regions with the most garbage first. Uses a remembered set and OopMap to track references, and performs phases: Initial Mark, Concurrent Mark, Final Mark, and Cleanup.

14. Three‑Color Marking

During concurrent marking, objects are colored:

White – not yet visited (garbage if still white after marking).

Black – live objects.

Gray – visited but may still have references to unvisited objects.

Incorrect markings can occur when objects change state during concurrent phases, requiring incremental updates or SATB (Snapshot‑At‑The‑Begin) techniques.

15. When Does Stack Memory Overflow Occur?

When a thread requests a stack larger than the JVM‑defined maximum, resulting in StackOverflowError.

When the JVM cannot allocate additional memory for stack expansion or for creating a new thread, resulting in OutOfMemoryError.

16. How to Diagnose OOM Issues

Enable heap dumps:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heapdump.hprof

.

Monitor memory and GC activity with jstat to locate the problematic region.

Analyze the heap dump with profiling tools to identify large object allocations.

17. Class Loading Mechanism

The JVM loads class files into memory, verifies, prepares, resolves, and initializes them. The order is fixed: loading → verification → preparation → (optional) resolution → initialization → unloading.

18. Parent‑Delegation Model Class loaders delegate loading requests to their parent loaders before attempting to load themselves, ensuring that core classes (e.g., java.lang.Object ) are loaded by the bootstrap loader and remain unique across the JVM. 19. Stack Allocation of Objects Objects that do not escape the current thread can be allocated on the stack, reducing heap pressure. Escape analysis determines whether an object is eligible for stack allocation. 20. Object Memory Layout Typical Java object layout consists of: Object Header : MarkWord (lock/status bits) and Class Pointer . Length : present only in arrays, stores the array size. Instance Data : the actual fields of the object. Padding : ensures the total size is a multiple of 8 bytes for alignment.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMMemory ManagementGarbage Collectioninterview
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.