Scrivio Interview library
ConceptPrincipal7 min read · updated 12 November 2026

Java has moved away from cleanup driven by garbage collection: finalization was deprecated for removal in Java 18 (JEP 421), with Cleaner, ClassValue and explicit close as the alternatives, while WeakHashMap remains. What does this tell you about building on GC-driven lifecycles, and what policy would you set?

It tells us that the garbage collector is a memory manager, not a resource manager: it runs when the heap needs space, so anything we tie to it happens at an unpredictable time, on an unknown thread, or not at all. Finalization was deprecated for removal because it was slow, unsafe and unpredictable, while weak references survive because they are useful for one narrow job, letting metadata disappear with objects owned elsewhere. The policy I would set is that resources are always released explicitly, with try-with-resources or lifecycle callbacks, Cleaner is only a safety net, and per-class data uses ClassValue.

Background to this question

Every long-lived Java system eventually meets a resource leak that looked impossible: files that stay open, connections that pile up, native memory that grows while the heap looks healthy. Often the root cause is code that expected the garbage collector to clean up. A senior engineer is expected to know why the platform itself has been moving away from that model and to turn that history into rules a whole organisation can follow. In this answer, we will look at what the GC actually promises, why finalization failed, what weak references and Cleaner are good for, and the policy that follows, with examples of how it applies in practice.

1What the Garbage Collector Actually Promises

The GC promises one thing: an object that can no longer be reached will eventually have its memory reclaimed, if the heap needs the space. It does not promise when, and it does not promise at all if memory is plentiful. A service with a 16 GB heap and light traffic may go minutes or hours without a full collection of its old generation.

So any action we attach to an object becoming unreachable inherits this timing. A file handle, socket or database connection is a scarce operating system or server resource with limits measured in hundreds or thousands, while the heap is measured in gigabytes. The heap can be nowhere near full while we run out of file descriptors. Tying the release of a scarce resource to the management of a plentiful one is the basic mismatch.

2Why Finalization Is Being Removed

Object.finalize() was the original way to run code before an object was reclaimed. JEP 421 in Java 18 deprecated it for removal, and the reasons are a good summary of everything wrong with GC-driven cleanup.

First, cost: an object with a finalizer must be tracked from creation, survives at least one extra collection cycle, and is processed by a finalizer thread, which slows allocation and collection. Second, safety: the finalize method can store this into a static field, resurrecting an object the GC had decided was dead, and finalizers can run while other methods of the same object are still executing in some edge cases. Third, unpredictability: finalizers run on an unspecified thread, in no particular order, possibly never, and an exception thrown inside one is silently ignored. A slow finalizer can block the queue and cause an OutOfMemoryError because objects waiting for finalization cannot be freed.

GC-driven cleanup mechanisms
MechanismStatusGood for
finalize()deprecated for removal (JEP 421)nothing new; remove existing uses
Cleanersupported since Java 9a safety net behind close()
WeakReference / WeakHashMapsupportedmetadata attached to objects owned elsewhere
ClassValuesupported since Java 7per-class computed data
try-with-resources / close()the primary mechanismfiles, sockets, connections, locks
Only the last row releases resources at a predictable moment.

3What Weak References Are Still Good For

WeakHashMap and WeakReference remain because they do a job that has nothing to do with releasing resources. They let us attach information to an object without extending its life. A serializer can remember per-object state, a profiler can tag objects, and a framework can keep a registry of listeners that disappears when the listener is gone. In all these cases, nothing bad happens if the entry lingers for a while after its key becomes unreachable. The only cost of late cleanup is some memory, and memory is exactly what the GC manages well.

That gives us the test for any GC-driven design: if the cleanup were delayed by an hour, or never happened, would anything other than heap usage suffer? If the answer is yes, the design must not depend on the GC.

4Explicit Release With a Cleaner Safety Net

The primary mechanism for resources is explicit release at a known point. In plain Java that means implementing AutoCloseable and using try-with-resources, which calls close() even when an exception is thrown. In Spring, beans that own resources release them in a @PreDestroy method or a DisposableBean callback, which run when the application context shuts down.

java.lang.ref.Cleaner, added in Java 9, can register an action to run after an object becomes phantom reachable. Unlike finalize, the action is a separate object that cannot see or resurrect the owner, and it runs on a Cleaner thread we control. We use it only as a safety net: close() does the real work and also runs the cleanable, which guarantees the action runs at most once, and the Cleaner catches the case where a caller forgot to close.

Java
public final class NativeBuffer implements AutoCloseable {
private static final Cleaner CLEANER = Cleaner.create();
private final Cleaner.Cleanable cleanable;
public NativeBuffer(long size) {
long address = Native.allocate(size);
// The state must not refer to 'this', or the buffer never becomes unreachable
this.cleanable = CLEANER.register(this, () -> Native.free(address));
}
@Override public void close() { cleanable.clean(); } // explicit, runs the action once
}
try (NativeBuffer buf = new NativeBuffer(1 << 20)) {
// use the buffer
} // freed here, deterministically; the Cleaner only covers a forgotten close()

Notice the comment in the constructor. The cleaning action is a lambda that captures only the address. If it captured the NativeBuffer itself, the Cleaner would hold the object strongly and the action would never run, the same trap as a WeakHashMap value that refers to its key.

5The Policy I Would Set

I would write the policy as a short rule with reasons, so teams understand it rather than just follow it. Every class that owns a file, socket, connection, lock, thread pool or native memory implements AutoCloseable or has a lifecycle callback, and every caller releases it with try-with-resources or through the container. No new code overrides finalize, and existing uses are migrated; the JDK flag --finalization=disabled, available since Java 18, lets us test a service with finalization turned off before it is removed for good. Cleaner is allowed only as a safety net behind close(), and it should log when it actually fires, because that means a caller leaked. Weak references are allowed for metadata about objects owned elsewhere, never for resources and never as a cache, which should be a bounded cache such as Caffeine. Per-class data uses ClassValue, which avoids keeping class loaders alive in maps keyed by Class.

Enforcement follows the same pattern as any platform rule: static analysis that flags finalize overrides and unclosed AutoCloseables, a code review checklist item for resource ownership, and a test run with finalization disabled. The design reason behind all of it is the same lesson the JDK learned: lifecycle that matters to correctness must be explicit and visible in the code.

6Follow-up questions

Why is ClassValue better than a WeakHashMap keyed by Class?

A WeakHashMap<Class<?>, V> keeps the value strongly. If that value refers to the class, for example a list of its Field or Method objects, the class stays strongly reachable through the map, and so does its class loader and every class it loaded. In application servers that redeploy, this is a classic leak. ClassValue stores the computed value in a way tied to the class itself, so the value becomes unreachable together with the class.

If Cleaner can still run late, why keep it at all?

Because a safety net that runs late is better than none for some resources, especially native memory that the GC cannot see. It turns a permanent leak caused by a forgotten close() into a delayed release, and logging when it fires tells us which caller to fix. It must never be the normal path.

How does this apply to Spring applications?

Beans that own resources should release them in @PreDestroy or through destroyMethod, which Spring infers for close() and shutdown() methods on @Bean definitions. Resources used per request, such as streams, belong in try-with-resources. Connection pools like HikariCP close their connections when the context shuts down, which is explicit, predictable cleanup.

7Conclusion

In this answer, we saw that the GC runs when memory is needed, not when resources should be released, so cleanup tied to it is unpredictable. Finalization was deprecated for removal because it was costly, could resurrect objects and ran on an unspecified thread. Weak references survive because they are right for metadata attached to objects owned elsewhere. The resulting policy releases resources explicitly with try-with-resources and lifecycle callbacks, keeps Cleaner only as a safety net, and uses ClassValue for per-class data.

What to say in the interviewAbout 80 seconds aloud

Open with

What the history tells me is that the garbage collector manages memory, not resources. It runs when the heap needs space, which may be rarely, so anything tied to it happens at an unpredictable time.

Then, if they want more

A service can run out of file descriptors or database connections with the heap half empty. Finalization showed every problem with that model: finalizable objects cost extra at allocation and collection, finalize could resurrect objects, it ran on an unspecified thread in no order, maybe never, and exceptions were swallowed.

That is why JEP 421 deprecated it for removal in Java 18. WeakHashMap survives because it does a different job: letting metadata disappear with objects someone else owns, where late cleanup only costs memory. The policy I would set is simple.

Anything that owns a file, socket, connection or native memory implements AutoCloseable or uses a lifecycle callback like @PreDestroy, and callers use try-with-resources. No new finalize methods, and we test with finalization disabled. Cleaner is only a safety net behind close, and it logs when it fires because that means a leak.

Weak references are fine for metadata, never for resources or caches. Per-class data goes in ClassValue to avoid class loader leaks. I would back it with static analysis and a review checklist.

About this answer

Last updated
12 November 2026
Versions it names
Java 18, Java 9
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.
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 "Java has moved away from cleanup driven by garbage collection: finalization was...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/069df5ea05/