Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Why was finalize() deprecated (and deprecated for removal since JDK 18), and what are Cleaner and try-with-resources used for instead?

finalize() was deprecated because it ties cleanup to garbage collection: a finalizer runs at an unpredictable time, on a thread we do not control, possibly never, and every finalizable object makes allocation and collection slower. Finalizers can also bring dead objects back to life and silently swallow their own exceptions. JEP 421 in JDK 18 deprecated finalization for removal; we now release resources deterministically with try-with-resources, and use java.lang.ref.Cleaner only as a safety net for callers who forget to close.

Why this question is asked

Most of us never write a finalize() method today, but we still meet them in old libraries, and we still have to answer the question behind them: who releases a file handle, a socket or a block of native memory, and when? Interviewers ask about finalization because the answer shows whether we understand the difference between memory, which the garbage collector manages, and other resources, which it does not. In this answer, we will recap what a finalizer was meant to do, look at why it failed in practice, see what JEP 421 changed, and then write the two replacements: try-with-resources for normal cleanup and Cleaner for the safety net.

1A Quick Recap of What finalize() Was For

Every Java object can be collected by the garbage collector once nothing references it. That is fine for memory, but some objects hold something the collector knows nothing about: an open file descriptor, a database connection or memory allocated outside the heap. If such an object is collected without releasing that resource, the resource leaks.

Java 1.0 offered a hook for this. A class could override Object.finalize(), and the collector promised to call it at some point after the object became unreachable and before its memory was reused. The idea was that the object could close its own resources at the last moment. It sounded convenient, and it turned out to be one of the most troublesome features in the language.

2Why Finalizers Fail in Practice

The first problem is timing. The collector decides when to run, and it only runs when the heap needs space. A program that opens many files but allocates little memory can run out of file descriptors long before a collection happens, so the finalizers that would have closed those files never get a chance. The specification does not even promise that finalizers run at all before the JVM exits.

The second problem is the thread. Finalizers run on a special finalizer thread that the JVM owns. If one finalize() method blocks, for example on a lock or a slow network close, every other finalizable object waits behind it in the queue, and their memory cannot be reclaimed either. Services have run out of memory simply because the finalizer thread fell behind.

The third problem is cost. When we allocate an object whose class has a finalizer, the JVM must register it at allocation time. When it becomes unreachable, the collector cannot free it in the first cycle; it must keep it alive, queue it, run finalize(), and free it only in a later cycle. So finalizable objects survive longer, are promoted to the old generation more often, and slow both allocation and collection.

Java
class Resurrect {
static Resurrect saved;
@Override protected void finalize() {
saved = this; // the dead object is reachable again
throw new RuntimeException("oops"); // ignored: nobody ever sees this exception
}
}
new Resurrect();
System.gc(); // a request, not a command
Thread.sleep(100);
System.out.println(Resurrect.saved != null); // usually true: the object came back
Step throughThe life of a finalizable object
  1. new Resurrect()the JVM registers the object for finalization
  2. Object becomes unreachablenothing in our code refers to it
  3. First GC cyclecannot free it; puts it on the finalizer queue
  4. Finalizer thread runs finalize()some time later, on a thread we do not own
  5. Did finalize() store this somewhere?
    YesObject is alive againNoFreed in a later GC cycle

5 steps in order. Play them, or step through them one at a time.

A normal object is freed in one cycle. A finalizable one needs at least two, and its timing depends on a single background thread.

The code shows two more problems. A finalizer can store this in a static field and resurrect the object, so an object we thought was gone is in use again, possibly in a half-cleaned state. That was also a security hole: an attacker's subclass could resurrect a partially constructed object whose constructor had thrown. And any exception thrown inside finalize() is silently ignored, so bugs in cleanup code stay hidden.

3What JEP 421 Changed

finalize() was deprecated in Java 9, but only as a warning. JEP 421, delivered in JDK 18, went further and deprecated finalization for removal, which means a future JDK may remove it entirely. The compiler now warns when we override finalize(), and the JDK's own classes such as FileInputStream and ZipFile had already moved their cleanup to other mechanisms.

JEP 421 also added a command-line option so we can find out whether our application depends on finalization before it disappears. Running with --finalization=disabled makes the JVM skip finalizers completely: objects are still collected, but finalize() is never called. If the application keeps working and its file descriptors and native memory stay flat, it does not depend on finalizers. If something leaks, we have found a dependency to fix.

4Fix 1: Deterministic Cleanup With try-with-resources

The real fix is to release resources at a moment we choose, not at a moment the collector chooses. A class that owns a resource implements AutoCloseable, and the caller uses try-with-resources, which calls close() automatically when the block ends, whether it ends normally or with an exception.

Java
final class TempBuffer implements AutoCloseable {
private final Arena arena = Arena.ofConfined(); // native memory, Java 22+
final MemorySegment segment = arena.allocate(1024);
@Override public void close() { arena.close(); } // memory released right here
}
try (TempBuffer buf = new TempBuffer()) {
buf.segment.set(ValueLayout.JAVA_INT, 0, 42);
} // close() runs here, always

Notice that the resource is released at the closing brace, every time, on our own thread. If close() throws while another exception is already in flight, try-with-resources keeps the first exception and attaches the second one as a suppressed exception, so nothing is lost. This is why every modern resource API, from streams to JDBC connections, implements AutoCloseable.

5Fix 2: Cleaner as a Safety Net

try-with-resources only helps when callers use it. For a library that hands out resources, we also want a fallback for the caller who forgets. That is what java.lang.ref.Cleaner, added in Java 9, is for. We register the object and a cleaning action; when the object becomes phantom reachable, meaning it is unreachable and can no longer be resurrected, the Cleaner's thread runs the action once. If close() is called first, the action runs then instead and never runs again.

Java
public final class NativeHandle implements AutoCloseable {
private static final Cleaner CLEANER = Cleaner.create();
// A static nested class: it must not hold a reference to NativeHandle
private static final class State implements Runnable {
private final long address;
State(long address) { this.address = address; }
@Override public void run() { Native.free(address); } // runs at most once
}
private final Cleaner.Cleanable cleanable;
public NativeHandle() {
long address = Native.allocate(4096);
this.cleanable = CLEANER.register(this, new State(address));
}
@Override public void close() { cleanable.clean(); } // normal path
}

The one rule that matters here is that the cleaning action must not reference the object it cleans. If State were an inner class or a lambda that captured this, the Cleaner would hold a strong reference to the NativeHandle through its action, the handle would never become unreachable, and the action would never run. So we put exactly the data needed for cleanup, here the native address, into a separate static class.

Cleaner fixes most of what was wrong with finalize(): the action cannot resurrect the object, it runs at most once, and we can run it ourselves through clean(). But it is still tied to garbage collection, so its timing is still unpredictable. That is why it is only a safety net, not the main path.

6Follow-up questions

Why can a Cleaner action not be a lambda that uses this?

Because the Cleaner keeps a strong reference to the action until it runs. If the action refers to the object, directly or through a captured field access, the object stays reachable from the Cleaner forever, so it never becomes phantom reachable and the action never runs. The leak we wanted to prevent becomes permanent. A static nested class or a lambda that captures only the resource values avoids this.

Does System.gc() make finalizers or Cleaner actions run?

Not reliably. System.gc() is a request the JVM may ignore, and even when a collection happens, the finalizer or Cleaner thread runs later. Tests that call System.gc() and then check whether cleanup ran are flaky by design. Tests should check that close() releases the resource instead.

7Conclusion

In this answer, we saw that finalize() tied resource cleanup to the garbage collector, which runs when memory is short rather than when resources are. Finalizers ran late or never, on a single thread we do not control, slowed allocation and collection, could resurrect objects and hid their own exceptions. JEP 421 in JDK 18 deprecated finalization for removal and added --finalization=disabled for testing. The replacements are try-with-resources with AutoCloseable for deterministic cleanup, and Cleaner as a safety net whose action never refers to the object it cleans.

What to say in the interviewAbout 80 seconds aloud

Open with

finalize was deprecated because it ties cleanup of non-memory resources to garbage collection, and the collector runs when the heap is short of space, not when we are short of file handles or native memory.

Then, if they want more

So finalizers run late, on a single JVM-owned finalizer thread, sometimes never. Each finalizable object is registered at allocation and needs at least two GC cycles to be freed, which slows allocation and collection, and a slow finalizer can back up the whole queue.

A finalizer can also store this in a static field and resurrect the object, which was a security issue, and any exception it throws is silently dropped. JEP 421 in JDK 18 deprecated finalization for removal, and we can run with --finalization=disabled to check whether anything still depends on it.

Instead, I make resource-owning classes implement AutoCloseable so callers use try-with-resources and the resource is released at the end of the block.

For libraries, I add a Cleaner registration as a safety net: the cleaning action is a static class holding only the handle, never a reference to the object itself, otherwise the object stays reachable and the action never runs.

About this answer

Last updated
12 November 2026
Versions it names
Java 18, Java 9, Java 22
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 "Why was finalize() deprecated (and deprecated for removal since JDK 18), and what are...": https://scrivio-interview-library.netlify.app/java/object-contracts/7a6aef0507/