Java Memory APIs & Diagnostics
The Java-level memory APIs and diagnostics that sit on top of the JVM: soft, weak and phantom references, ReferenceQueue and Cleaner, the OutOfMemoryError and StackOverflowError families, classic leak patterns, and the tooling to find them. Senior interviews almost always include a production memory-problem scenario, and this is the vocabulary for answering it.
part ofJavaoverview, primer and where to startread it →on this pageshowhide
explore
- Bridge: JVM Platform Internals6 questions
- Strong References4 questions
- Soft References4 questions
- Weak References & WeakHashMap5 questions
- Phantom References, ReferenceQueue & Cleaner5 questions
- Memory Leak Patterns5 questions
- ClassLoader Leaks5 questions
- OutOfMemoryError Variants5 questions
- StackOverflowError4 questions
- Heap Dumps & Profiling Tools5 questions
questions
page 2 of 2Explain how unremoved listeners and ThreadLocals in pooled threads cause leaks, and how you avoid them.
basics
~20 sIf you register a listener and never remove it, the event source keeps your object alive. A ThreadLocal value stays alive as long as the thread does — and pool threads live forever, so the value never goes away. Always deregister listeners and always call ThreadLocal.remove() in pooled code.
What does 'OutOfMemoryError: GC overhead limit exceeded' mean, and how does it differ from a plain 'Java heap space' error?
basics
~20 sIt means the garbage collector is working almost constantly (about 98% of the time) but barely freeing anything (less than 2% of the heap). The JVM gives up early instead of thrashing. It's an early-warning version of a heap problem: the heap is nearly full and the program is spending all its time collecting instead of doing real work.
What is 'OutOfMemoryError: Metaspace', what kinds of problems produce it, and how does it differ from a heap-space OOME?
basics
~20 sMetaspace is the area that stores class metadata (the definitions of loaded classes), separate from the object heap. This OOME means too many classes are loaded — often because classes keep being created (dynamic proxies, code generation) or because old classes can't be unloaded (a classloader leak). Heap-space OOME is about objects; Metaspace is about class definitions.
What is the java.lang.ref.Cleaner API, and why did it replace Object.finalize()?
basics
~20 sCleaner (Java 9+) is the modern, safe way to run cleanup when an object becomes unreachable. You register an object plus a cleanup action; Cleaner runs it later on a background thread. It replaced finalize() because finalizers were unpredictable, slow, and could resurrect objects or fail silently.
How does a ReferenceQueue underpin soft, weak, and phantom reference notification?
basics
~20 sA ReferenceQueue is a queue the garbage collector puts reference objects onto after it clears their referent. You register a reference with a queue; later you poll or block on that queue to find out the object was collected, then react (usually cleanup).
What are the pitfalls of building a cache out of SoftReferences, and why are bounded caches like Caffeine usually preferred?
basics
~20 sA soft-reference cache has no size limit and no real eviction rules of its own — it just hopes the garbage collector will clear things at the right time. Under memory pressure it can dump everything at once and slow the app down. A real cache library lets you set size and time limits, so it behaves predictably.
What does the -Xss flag do, and when is increasing it the right response to a StackOverflowError?
basics
~10 s-Xss sets each thread's stack size. A bigger value allows deeper recursion before a StackOverflowError. It only helps when recursion is legitimately deep but finite — it cannot fix recursion that never ends.
How can code that uses only ordinary strong references still cause a memory leak in a garbage-collected JVM?
basics
~20 sEven with a GC, you leak when objects stay strongly reachable but are never used again. Things like an ever-growing static list, listeners never removed, or ThreadLocals not cleared keep strong references alive, so the GC can't reclaim them.
How does WeakHashMap work, what is it useful for, and what are its common pitfalls?
basics
~20 sWeakHashMap is a map that holds its keys with weak references. When a key is no longer used anywhere else, the garbage collector reclaims it and the map automatically removes that entry, so the map can't keep old keys alive.
How do you design Java systems to be resistant to memory leaks, rather than just diagnosing them after the fact?
basics
~20 sMake object ownership and lifetime explicit. Never use unbounded caches — always bound size or add expiry. Pair every register/open/subscribe with an unregister/close/unsubscribe, ideally with try-with-resources. Clear ThreadLocals in pooled code. And watch live heap in production so slow leaks are caught early.
Explain how strong reachability from GC roots determines object liveness, and why this is a JVM platform mechanism rather than a Java language feature.
basics
~20 sThe JVM keeps an object alive if it can be reached from a starting point it trusts (a GC root) by following references. The strong reference is the Java keyword-free, ordinary handle you write; reachability from roots is the runtime rule the JVM applies to decide what survives.
What role does a ReferenceQueue play with weak references, and how is it used to detect reclamation?
basics
~20 sA ReferenceQueue is a notification channel. You register a weak reference with a queue when you create it, and after the garbage collector clears that reference, it places the reference object on the queue. Polling the queue tells you which referents have been collected.
From an architecture standpoint, how do you design plugin/redeploy systems to be resistant to classloader leaks?
basics
~20 sGive each plugin/app its own classloader, never let long-lived infrastructure hold strong references to plugin objects (use weak references and explicit deregistration), and clean up threads, ThreadLocals, drivers, and listeners on undeploy. Test by redeploying many times and confirming the old classloader is collected.
Heap dumps pause the JVM and can be gigabytes. How do you design a production memory-diagnostics strategy that gets you actionable data without destabilizing the service?
basics
~20 sRely on always-on low-overhead tools like Java Flight Recorder and GC logs for continuous insight, and reserve full heap dumps for when you really need object-level detail. When you must dump, do it on one instance taken out of rotation, write to fast local disk, and have a plan for where dumps go and how sensitive data in them is protected.
You own a class wrapping an off-heap buffer. How do you design its resource cleanup using AutoCloseable and a Cleaner backstop, and what are the pitfalls?
basics
~20 sMake the class AutoCloseable so callers free the buffer promptly with try-with-resources. Also register it with a Cleaner as a safety net if they forget. Put the buffer handle in a separate state object the cleanup doesn't tie back to the wrapper, and make close() and the Cleaner path idempotent.
How does HotSpot decide when to clear soft references, and how does that interact with heap sizing, GC choice, and the SoftRefLRUPolicyMSPerMB flag?
basics
~20 sHotSpot keeps a soft-referenced object based on how much free memory there is and how long ago it was last used: more free memory means it lives longer. A JVM flag controls that ratio. Because it depends on free heap, the same code keeps soft references for different amounts of time depending on heap size and the garbage collector you run.
Why doesn't the JVM eliminate deep tail recursion automatically, and what are your options to make deeply recursive Java algorithms safe?
basics
~20 sStandard Java/HotSpot does not do tail-call optimization, so even tail-recursive methods keep pushing stack frames and can overflow. To make deep recursion safe, rewrite it as a loop, often with your own explicit stack on the heap.
Weak references prevent some leaks but can hide others. When are they the right design tool, and what failure modes should you watch for?
basics
~20 sWeak references are good when you must associate data with objects you don't own and want that data to disappear automatically when those objects are no longer used. They go wrong when something still strongly holds the object, when you assume entries vanish on a schedule, or when an explicit bounded structure would be simpler.
showing 31–48 of 48