JVM Memory Management, Singleton Design, and SOLID
System DesignModel answerLast updated
Explain how the JVM reclaims memory, how to implement a Singleton safely in Java, and how SOLID principles lead to maintainable, extensible object-oriented designs.
You are being interviewed on your understanding of core Java runtime and design fundamentals. Answer the following in prose, using small code snippets where they clarify the point:
-
Memory management: Describe at a high level how the JVM decides an object is garbage, how generational collection works (Eden, survivor spaces, the old generation, promotion), and what mark, sweep, and compaction each accomplish. Name a couple of available collectors and explain the diagnostic signals and tuning knobs you would look at in production.
-
One instance per program: Define the Singleton pattern, describe when it is justified, and discuss the usual objections — testability, hidden dependencies, global mutable state, reflection and deserialization. Show how you would implement it in Java so that it is thread-safe and, if laziness is desired, still safe under concurrent access. Contrast eager, lazy, and dependency-injected approaches.
-
Object-oriented design: Walk through the core OOP ideas (encapsulation, abstraction, inheritance, polymorphism) and the SOLID principles, explaining concretely how each one improves maintainability or extensibility. Point out where SOLID is over-applied.
Aim for a mental model rather than memorized terms: state trade-offs, mention real failure modes, and explain what you would actually do in a codebase.
Hints
Hint 1
GC collects by reachability from roots, not by reference counting — cycles are not a problem.
Hint 2
Class initialization guarantees thread-safe lazy construction; double-checked locking needs a volatile field.
Hint 3
Each SOLID letter should be tied to a specific design benefit, plus a warning about over-engineering.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. How the JVM reclaims memory
The garbage collector works by tracing reachability. It starts at GC roots — local variables on thread stacks, static fields, live threads, JNI handles — and follows references outward. Anything it cannot reach is garbage and its memory may be reclaimed. Because the GC traces outward, two objects that reference only each other and nothing live are still collected; reference counting is not involved.
The design rests on the generational hypothesis: most objects die shortly after allocation. The heap is therefore split by age:
- Eden receives nearly all new allocations. Allocation is a fast pointer bump, usually served from a thread-local allocation buffer.
- Survivor spaces (S0 and S1) hold objects that survived a young collection.
- A minor (young) GC copies live objects from Eden plus the active survivor space into the other survivor space. Copying is cheap because the live set is small, and it leaves the space compacted for free. Objects that survive enough collections (the tenuring threshold) are promoted into the old generation.
- The old generation holds long-lived data and is collected less often. Class metadata lives in Metaspace (native memory since Java 8).
A full collection is classically described as mark (mark reachable objects), sweep (reclaim unmarked blocks), and compact (slide survivors together and repair references). Compaction is the expensive step. Write barriers and card tables record old-to-young references so a minor GC need not scan the entire old generation.
Collector choices worth knowing: Parallel GC maximizes throughput with stop-the-world pauses; G1 (the default since JDK 9) divides the heap into regions and collects the regions with the highest garbage ratio first, aiming at a pause goal such as -XX:MaxGCPauseMillis=200; ZGC and Shenandoah do most of their work concurrently and target very low pause times on large heaps.
Diagnostics. I look at pause distribution and frequency (-Xlog:gc*, JFR, jstat -gcutil), allocation rate, promotion rate, and old-generation occupancy after a full collection. A young-generation pause storm is usually an allocation-rate problem — string concatenation, boxing, or temporary objects in a hot loop — and fixing the code beats raising flags. Objects promoted prematurely suggest the young generation or survivor space is too small. Old-gen occupancy that keeps climbing after full GCs is the classic leak signature: unbounded static caches, listeners never removed, or ThreadLocal values never cleared on pooled threads. I enable -XX:+HeapDumpOnOutMemoryError and analyze dumps with Eclipse MAT. Errors like OutOfMemoryError: Java heap space, GC overhead limit exceeded, and OutOfMemoryError: Metaspace point at different problems — heap retention, an allocation pathology, or a classloader leak. Practical knobs: set -Xms equal to -Xmx to avoid resizing, size the young generation deliberately, and choose a collector based on latency versus throughput needs. Never tune blind; measure first.
2. The Singleton pattern
A Singleton is a class that guarantees exactly one instance per classloader and exposes a global access point. The idiom:
public final class Registry {
private static final Registry INSTANCE = new Registry();
private Registry() {}
public static Registry getInstance() { return INSTANCE; }
}
This eager form is thread-safe because the JVM guarantees class initialization happens exactly once and publishes the result safely.
For lazy initialization, use the initialization-on-demand holder idiom — also thread-safe without locking, because the inner class is initialized on first access:
public final class Registry {
private Registry() {}
private static class Holder {
static final Registry INSTANCE = new Registry();
}
public static Registry getInstance() { return Holder.INSTANCE; }
}
An enum is the most robust variant, since it resists reflection and deserialization (each constant is deserialized to the same object):
public enum IdGenerator {
INSTANCE;
private final AtomicLong next = new AtomicLong();
public long nextId() { return next.incrementAndGet(); }
}
If you do use double-checked locking, the field must be volatile; otherwise another thread can observe a non-null reference to a partially constructed object:
public final class Cache {
private static volatile Cache instance;
private Cache() {}
public static Cache getInstance() {
Cache local = instance;
if (local == null) {
synchronized (Cache.class) {
local = instance;
if (local == null) instance = local = new Cache();
}
}
return local;
}
}
Where it fits: a genuinely process-wide, immutable or stateless resource — a metrics registry, a configuration snapshot, a connection-pool manager. Even then, in a modern Spring service I would usually let the DI container own the singleton scope rather than hard-coding getInstance(). The container gives me the same "one instance" guarantee while keeping the dependency visible in the constructor and substitutable in tests.
Common pitfalls:
- Hidden dependencies:
Cache.getInstance()buried inside a method does not appear in a signature, so readers and tests cannot see or substitute it. - Testability: mocks are hard to inject, and mutable singleton state leaks between tests, producing order-dependent failures.
- Global mutable state: concurrent mutation from many callers invites race conditions and tight coupling.
- Broken uniqueness: reflection can bypass a private constructor, deserialization creates a new instance unless
readResolveis implemented, and separate classloaders legitimately yield separate instances. - Eager vs lazy: eager is simplest and fine when construction is cheap; lazy avoids paying for an object that is never used. The holder and enum forms give laziness for free, so hand-rolled locking is rarely worth it.
3. OOP and SOLID
Encapsulation hides state behind behavior so invariants cannot be violated externally. Account.withdraw(amount) validates the balance internally; exposing setBalance would let any caller break the rule that the balance is non-negative.
Abstraction exposes what an object does while hiding how. A PaymentGateway interface lets the caller depend on the contract, not on HTTP details.
Inheritance models an "is-a" relationship and shares implementation, but it couples subclasses to the parent — prefer composition when the relationship is merely "has-a".
Polymorphism lets callers program against a supertype or interface so new implementations can be substituted without touching callers. This is the single biggest lever on extensibility: adding a new payment provider should require no change to the checkout service.
SOLID, concretely:
- Single Responsibility: a class should have one reason to change. Splitting HTTP parsing, business rules, and persistence means a change in one area does not force you to retest the others.
- Open/Closed: extend behavior by adding new classes rather than editing existing ones — e.g., new strategies implementing a
PricingRuleinterface. - Liskov Substitution: a subclass must honor the parent's contract. If
Squarecannot honorRectangle.setWidth/ setHeightsemantics, do not subclassRectangle. - Interface Segregation: narrow interfaces beat fat ones. Depend on
ReadableandWritablerather than a singleDataStreamwith unused methods. - Dependency Inversion: high-level policy should not depend on low-level details; both should depend on abstractions, so the domain is testable with in-memory fakes.
Trade-off: SOLID is a tendency, not a law. Splitting a class into ten one-method classes to satisfy "SRP" can make the system harder to navigate. I apply the principles where a real change or a real test boundary justifies the seam, and prefer plain readable code elsewhere. The goal is not maximal abstraction but low cost of change.