First read the message, since heap space, metaspace, direct buffer and GC overhead limit exceeded point at very different causes. Run with heap dump on out of memory so you capture the state at failure, then open the dump in a memory analyzer and look at the dominator tree to see what retains the most. Compare dumps over time to separate a genuine leak from a working set that is simply larger than the heap.
Why interviewers ask this
The interviewer wants a repeatable method and familiarity with the tooling. Distinguishing the error variants is a fast credibility signal, as is knowing the usual culprits: unbounded caches, thread locals on pooled threads, class loader leaks on redeploy, and queries that materialize a whole table. They are also checking that you will not simply raise the heap size and call it fixed.
How to structure your answer
- Read the specific error variant before theorizing.
- Capture a heap dump automatically at failure.
- Analyze retained size and the dominator tree, not shallow counts.
- Confirm the fix with a bounded cache or streamed query, then verify.
Example answer
The variant matters. Java heap space means live objects genuinely fill the heap, metaspace means classes are being loaded and never released, and a direct buffer error points at NIO or a native library rather than my objects. So I read that first, then make sure the JVM is running with heap dump on out of memory and a path on a volume that survives the restart, because guessing without a dump wastes days. With the dump I look at retained rather than shallow size, and the dominator tree usually names the culprit in a couple of minutes. What I actually find is repetitive: a map used as a cache with no eviction, a thread local set on a pooled thread and never cleared so it lives as long as the pool, or a repository method returning every row because someone dropped the pagination. I also check garbage collection logs to see whether the heap was climbing steadily or spiking on particular requests. The fix is bounding something, a cache with a maximum size and expiry, or streaming the query, and then I watch the live set across a week to confirm it is flat.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- How do you tell a leak from a working set that is just too big?
- What causes a metaspace error specifically?
- How do thread locals leak on a pooled thread?
Related java developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions