What is finalize()
in Java? Why is it Needed?
The finalize()
method in Java is a special method that is called by the Garbage Collector (GC) before an object is removed from memory. It was designed to allow cleanup actions before an object is garbage collected, but it is now deprecated (Java 9+).
1. Syntax of finalize()
The finalize()
method belongs to the Object
class and can be overridden in user-defined classes.
protected void finalize() throws Throwable {
// Cleanup code before GC
}
It is automatically called before an object is garbage collected. It is not guaranteed to run immediately or even at all. Since Java 9, it has been deprecated due to reliability issues.
2. Example of finalize()
class Example {
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize method called!");
}
public static void main(String[] args) {
Example obj = new Example();
obj = null; // Making the object eligible for GC
System.gc(); // Request GC (not guaranteed)
System.out.println("Main method finished");
}
}
Possible Output
Main method finished
Finalize method called!
🚀 The garbage collector may call finalize()
before deleting the object, but it is not guaranteed when (or if) it will run.
3. Why Was finalize()
Introduced?
finalize()
was initially designed for: ✅ Releasing non-Java resources (e.g., closing file handles, network connections).
✅ Performing cleanup before an object is destroyed.
✅ Providing a safety net for memory management (before modern GC improvements).
4. Problems with finalize()
🔴 Unreliable Execution – The JVM decides when to run the garbage collector, so finalize()
may never be called.
🔴 Performance Overhead – Slows down garbage collection because finalizable objects are treated specially.
🔴 Dangerous Resurrecting Objects – The object can be “revived” inside finalize()
, leading to unexpected behavior.
Example: Object Resurrection in finalize()
class Test {
static Test instance;
@Override
protected void finalize() {
instance = this; // Reviving the object
System.out.println("Object resurrected!");
}
public static void main(String[] args) {
Test obj = new Test();
obj = null;
System.gc(); // Request GC
if (instance != null) {
System.out.println("Object is still alive!");
} else {
System.out.println("Object was collected");
}
}
}
Output
Object resurrected!
Object is still alive!
🚨 Issue: Instead of getting garbage collected, the object was revived inside finalize()
.
5. finalize()
vs. Try-With-Resources (AutoCloseable
)
🔹 Better Alternative: Use AutoCloseable
and try-with-resources
instead of finalize()
.
✅ Example: Using AutoCloseable
for Resource Cleanup
class Resource implements AutoCloseable {
public void use() {
System.out.println("Using resource...");
}
@Override
public void close() {
System.out.println("Resource cleaned up!");
}
}
public class Main {
public static void main(String[] args) {
try (Resource res = new Resource()) {
res.use();
} // Automatically calls `close()`
}
}
Output
Using resource...
Resource cleaned up!
✔ No reliance on GC
✔ Guaranteed cleanup
6. Why Was finalize()
Deprecated?
Since Java 9, finalize()
has been deprecated due to its issues.
Java Documentation Warning
Warning: The finalize() method is deprecated and not recommended for use.
🔹 Instead of finalize()
, use proper resource management techniques like:
try-with-resources
for closing files/connections.- Explicit cleanup methods (
close()
,shutdown()
, etc.). - Weak references (
WeakReference
) for better memory handling.
7. Summary
Feature | finalize() |
---|---|
Purpose | Cleanup before GC |
Execution Guaranteed? | ❌ No |
Performance Impact | ❌ High |
Alternative? | ✅ try-with-resources , AutoCloseable |
Deprecated? | ✅ Yes (Java 9+) |
🚀 Final Verdict: Avoid using finalize()
and use proper resource management techniques like AutoCloseable
and try-with-resources
instead.