What is finalize() and Is It Reliable?
Fast recall
Quick revision
Core answer
Whether the candidate knows both what finalize() is and the critical reasons why it should not be used
Thinking finalize() is a reliable destructor like in C++ — it's not guaranteed to run, runs at unpredictable times, and can cause performance problems
Recommend try-with-resources and AutoCloseable as the correct modern alternative for resource cleanup
Interview-ready guide
Interview answer
Object.finalize was a legacy hook that the finalization mechanism might invoke after an object became unreachable. It was never a deterministic destructor: the JVM did not guarantee that it would run, and its timing could not define a safe resource lifetime. The method was deprecated in Java 9, and Java 18 deprecated finalization for removal; it was not simply removed in Java 18. Finalization also carries performance, security, and resurrection risks. A class that owns a file, socket, or connection should implement AutoCloseable, and callers should use try-with-resources so close runs at the end of a known scope even when the body throws.
What is finalize() and Is It Reliable
Direct Answer
Object.finalize() was a finalization hook that the JVM might invoke after an object became unreachable. Its execution and timing were never guaranteed. The method was deprecated in Java 9 and finalization was deprecated for removal in Java 18; saying it was removed in Java 18 is incorrect. Use AutoCloseable with try-with-resources for deterministic cleanup.
Code Example
import java.io.IOException;
import java.net.Socket;
final class ManagedConnection implements AutoCloseable {
private final Socket socket;
ManagedConnection(Socket socket) {
this.socket = socket;
}
@Override
public void close() throws IOException {
socket.close();
}
}
class CleanupExample {
static void send(Socket socket) throws IOException {
try (var connection = new ManagedConnection(socket)) {
// use connection
} // close() runs on normal or exceptional exit from the try body
}
}
The owner closes the resource at a known boundary. A finalizer cannot provide that timing guarantee.
Common Mistakes & Pitfalls
- Treating finalize like a deterministic destructor: finalization may happen late or never happen before process exit.
- Using it for resources: a file or connection can remain open while the application waits for an unpredictable GC decision.
- Saying Java 18 removed it: Java 18 deprecated finalization for removal; that is different from immediate removal.
- Replacing explicit ownership with Cleaner: Cleaner can be a last-resort safety net for some native resources, but normal cleanup should still be explicit.
Check your understanding
Answer these without looking back at the article.
- What is try-with-resources in Java?
- What is the AutoCloseable interface used for?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.