Quick revision
The short answer
The garbage collector runs when memory is short, not when file handles, sockets or native memory are short, so any cleanup tied to GC happens late, at an unpredictable time, or never. Finalizers showed this at its worst, with unpredictable timing, object resurrection, slower allocation and collection, and security problems, and JEP 421 deprecated them for removal; soft-reference caches showed a milder version, making heap usage and GC cost hard to predict. The standards that follow are to release resources explicitly with AutoCloseable and try-with-resources, to use Cleaner only as a safety net, to use explicitly bounded caches, and to flag finalize and soft-reference caches in static analysis.
What to remember
In this answer, we saw that the collector responds to heap pressure, not to pressure on file handles, sockets or native memory, so cleanup tied to GC is late and unpredictable. Finalizers showed this with unpredictable timing, resurrection, slower GC and security problems, and JEP 421 deprecated them for removal; soft-reference caches showed it with unpredictable heap usage and GC cost. The standards that follow are explicit release with AutoCloseable and try-with-resources, Cleaner only as a safety net, explicitly bounded caches, and static analysis that flags finalize and soft-reference caches.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The garbage collector runs when memory is short, not when file handles, sockets or native memory are short, so any cleanup tied to GC happens late, at an unpredictable time, or never. Finalizers showed this at its worst, with unpredictable timing, object resurrection, slower allocation and collection, and security problems, and JEP 421 deprecated them for removal; soft-reference caches showed a milder version, making heap usage and GC cost hard to predict. The standards that follow are to release resources explicitly with AutoCloseable and try-with-resources, to use Cleaner only as a safety net, to use explicitly bounded caches, and to flag finalize and soft-reference caches in static analysis.
Why this question is asked
Every few years a production incident turns out to have the same root cause: some resource was supposed to be released when an object was garbage collected, and it was not released in time. Files stay open until the process hits its descriptor limit, native memory grows until the container is killed, or a cache fills the heap. The JDK itself went through this lesson with finalization. Interviewers ask senior engineers this question to see whether they can extract a principle from history and turn it into standards for a codebase. In this answer, we will look at why the collector is the wrong trigger for non-memory resources, what went wrong with finalizers and soft-reference caches, and what standards follow.
1Why the Collector Is the Wrong Trigger
The garbage collector has one job: reclaim heap memory. It runs when the heap needs space, and its timing depends on allocation rate and heap size. It knows nothing about other resources. A service with a 4 GB heap might go minutes between old-generation collections, while opening 10,000 files during that time.
So if a file handle is released only when its owning object is collected, the handle stays open until the collector happens to process that object. The process can hit its file descriptor limit, say 65,536, while the heap is half empty and the collector sees no reason to run. The same goes for sockets, database connections, locks and native memory. The resource and the collector's trigger are measured in different units.
2What Went Wrong With Finalizers
Object.finalize() was Java's original answer: override it, and the JVM calls it before reclaiming the object. In practice it caused a list of problems, each rooted in tying cleanup to GC.
| Mechanism | Main problem | Replacement |
|---|---|---|
finalize() | late or never, resurrection, slow GC, security | close() + try-with-resources |
| Cleaner | still GC-timed if close() is forgotten | keep as a safety net only |
SoftReference cache | fills the heap, unpredictable GC cost | bounded cache: maximumSize/Weight |
WeakHashMap metadata | fine if values never reference keys | keep, with care |
Timing was unpredictable: finalize() ran only after a GC found the object unreachable, then waited in a queue for a single finalizer thread, and the JVM did not even promise to run it at all. Finalization also slowed the system: each finalizable object had to be registered at allocation, needed at least two GC cycles to be reclaimed, and if the finalizer thread fell behind, objects piled up until the JVM ran out of memory.
The code above shows resurrection: finalize() can store this somewhere, making a dead object live again in a half-cleaned state. And there was a security problem: if a constructor threw an exception partway through, a subclass's finalize() could still capture the partially built object and use it, bypassing the checks the constructor was meant to enforce. For all these reasons JEP 421 deprecated finalization for removal in JDK 18, and the JDK offers --finalization=disabled so we can test our applications without it.
3Soft-Reference Caches: A Milder Version of the Same Lesson
Soft references used GC as a cache eviction policy: keep everything, let the collector decide what to drop when memory is tight. The result was the same kind of unpredictability. Caches grew until the heap was nearly full, collectors worked constantly to keep a little space free, and how many entries survived depended on free heap and access times at the moment of each GC. Nobody could state the cache's size, memory use or hit rate.
The pattern is the same as with finalizers: a decision that belongs to the application, when to release a resource or which entry to evict, was handed to a mechanism built for something else, and the system lost predictability.
4The Standards That Follow
The first standard is explicit release. Any class that owns a non-memory resource implements AutoCloseable, and callers use try-with-resources, so the resource is released at a known point in the code, even when an exception is thrown.
The second standard is that Cleaner is a safety net, not the mechanism. Classes that wrap native resources may register a Cleaner action so a forgotten close() does not leak forever, but tests and reviews treat reliance on it as a bug, and the action may log a warning when it has to clean up something that was not closed.
The third standard is that caches have explicit limits: maximumSize or maximumWeight plus expiry, with size and hit rate metrics. Soft-value caches are not allowed without a written reason.
The fourth is enforcement. Static analysis flags any override of finalize(); javac already reports it with deprecation-for-removal warnings, and common analysers such as Error Prone, SpotBugs and Sonar have rules for finalizers and unclosed resources; check your tools for the exact rule names. We add a rule or a simple build check for new SoftReference-based caches. Before the JDK removes finalization, running the test suite with --finalization=disabled shows whether any dependency still relies on it, and JFR's finalizer statistics in recent JDKs show which classes still have finalizers at runtime.
5Follow-up questions
Is Cleaner just a better finalizer?
It fixes finalize's structural problems: the cleanup action cannot reach the object, so resurrection is impossible; clean() can run it explicitly exactly once; and each library can use its own thread. But its timing is still tied to GC when close() is not called, so it inherits the core problem. That is why it is a safety net, not the main release path.
What about resources inside frameworks, like Spring beans?
Frameworks follow the same principle with lifecycles: Spring calls destroy methods or close() on singleton beans when the context shuts down, and @PreDestroy marks such methods. The point is that release happens at a defined moment, not when the collector gets around to it.
How would you migrate a large codebase that still uses finalize?
First find all overrides with static analysis and the deprecation warnings. For each class, add AutoCloseable with an explicit close(), update callers to use try-with-resources, and replace finalize() with a Cleaner registration only if a safety net is really needed. Then run the test suite and a staging environment with --finalization=disabled to catch anything missed, including in third-party libraries.
6Conclusion
In this answer, we saw that the collector responds to heap pressure, not to pressure on file handles, sockets or native memory, so cleanup tied to GC is late and unpredictable. Finalizers showed this with unpredictable timing, resurrection, slower GC and security problems, and JEP 421 deprecated them for removal; soft-reference caches showed it with unpredictable heap usage and GC cost. The standards that follow are explicit release with AutoCloseable and try-with-resources, Cleaner only as a safety net, explicitly bounded caches, and static analysis that flags finalize and soft-reference caches.
Open with
The core lesson is that the garbage collector manages memory and nothing else. It runs when the heap needs space, not when we are running out of file descriptors, sockets or native memory, so any cleanup that waits for GC happens late, at an unpredictable time, or never.
Then, if they want more
A service can hit its file descriptor limit with the heap half empty.
Finalizers were the extreme case: they ran after a GC on a single finalizer thread with no guarantee, they could resurrect the object by storing this, finalizable objects slowed allocation and needed extra GC cycles, and a subclass finalizer could capture a partially constructed object, which was a security hole.
That is why JEP 421 deprecated finalization for removal in JDK 18. Soft-reference caches are a milder version: they let GC decide eviction, which makes heap usage and GC cost unpredictable. The standards I would set follow directly. Every class that owns a non-memory resource implements AutoCloseable and callers use try-with-resources.
Cleaner is allowed only as a safety net, and relying on it is treated as a bug. Caches are explicitly bounded with maximum size or weight and expiry, with metrics. And static analysis flags any finalize override and new soft-reference caches, while we run tests with --finalization=disabled to find dependencies that still rely on finalizers.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- HotSpot Garbage Collection Tuning Guide, JDK 21
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Finalization is deprecated for removal, and soft references are discouraged for caches....": https://scrivio-interview-library.netlify.app/java/garbage-collection/23b209d190/