Finalization in Java
What Is Finalization?
Finalization was an old Java mechanism that allowed an object to perform cleanup before the Garbage Collector removed it.
It used the finalize() method, which belonged to the Object class.
However, finalize() is deprecated (Java 9+) and removed in modern Java because:
- It is unpredictable
- Causes performance issues
- Can revive dead objects
- Bad for memory management
Why Was Finalization Introduced?
Originally, finalization was meant to:
- Clean up non-Java resources
- Close files
- Release native memory
- Perform last-moment cleanup
But later Java introduced try-with-resources and AutoCloseable, which made finalization unnecessary.
How Finalization Works (Conceptually)

1. GC Marks Object as Ready for Deletion
When an object becomes unreachable, GC prepares to remove it.
2. JVM Calls finalize() (Only Once)
If the class overrides finalize(), JVM may call it.
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize called!");
}
3. Object May Become Reachable Again (Object Resurrection)
Inside finalize(), you could write code that assigns the object to a static variable — this brings it back to life.
This is one major reason it was deprecated.
4. GC Runs Again and Deletes It
If not resurrected, GC deletes the object permanently.
Problems With finalize()
1. Unpredictable Execution : You never know when or if finalize() will run.
2. Causes Delays in Garbage Collection : Objects with finalize() go into a special queue → slower GC.
3. Object Resurrection Issue : An object can become alive again → leads to memory leaks.
4. Performance Overhead : GC becomes slower because it must process finalize-queue objects.
5. Not Reliable for Resource Cleanup : File handles or DB connections may remain open too long.
Why finalize() Was Deprecated?
- Poor performance
- Unreliable behavior
- Caused memory leaks
- Hard to debug
- Dangerous due to resurrection
- Encouraged bad coding practices
Java 9 marked it as:
@Deprecated(since="9", forRemoval=true)
Better Alternatives to Finalization
1. try-with-resources (Recommended)
Handles automatic closing of resources.
try (FileInputStream fis = new FileInputStream("a.txt")) {
// work
}
2. Implement AutoCloseable
class MyResource implements AutoCloseable {
public void close() {
System.out.println("Cleaned!");
}
}
3. Cleaner API (Java 9+)
A modern alternative to finalize().
Cleaner cleaner = Cleaner.create();
class Resource implements Runnable {
@Override
public void run() {
System.out.println("Cleaning...");
}
}
This is safe and predictable.
Points to Remember
- Finalization was used for cleanup but is now deprecated.
- finalize() is slow, dangerous, and unpredictable.
- Use try-with-resources, AutoCloseable, or Cleaner API instead.
- Knowing finalization is still important for interviews and legacy code.
