The finalize()
method in Java is part of the java.lang.Object
class and is called by the garbage collector when it determines that there are no more references to an object. This method provides an opportunity to perform cleanup operations, such as releasing resources like file handles or network connections, before the object is garbage collected.
Syntax of finalize()
Method:
protected void finalize() throws Throwable {
// Cleanup code
}
- The
finalize()
method isprotected
, which means it can be overridden in subclasses, but it cannot be accessed directly from outside the class. - It is called by the garbage collector before the object is actually removed from memory.
- It can throw a
Throwable
, but generally, exceptions are not expected to be thrown infinalize()
.
Key Points About finalize()
:
- Automatic Invocation: The garbage collector calls the
finalize()
method automatically before an object is garbage collected. You do not invokefinalize()
manually. - Unpredictable: The timing of the garbage collection process and the execution of
finalize()
are unpredictable. It may not even be called if the garbage collector does not deem it necessary to collect the object. - Deprecated in Java 9: As of Java 9, the
finalize()
method is deprecated, and it is recommended to use other mechanisms (such astry-with-resources
,AutoCloseable
, or explicit resource management) for resource cleanup.
How to Override the finalize()
Method:
To override the finalize()
method, you need to create a subclass of Object
(implicitly or explicitly), and then define the method in your class. Here’s an example:
Example: Overriding finalize()
Method
class MyClass {
private String resourceName;
// Constructor to initialize resource
MyClass(String resourceName) {
this.resourceName = resourceName;
}
// Overriding finalize method
@Override
protected void finalize() throws Throwable {
try {
// Cleanup code: e.g., release resources
System.out.println("Cleaning up resources for " + resourceName);
} finally {
// Ensure the superclass finalize() method is called
super.finalize();
}
}
}
public class FinalizeExample {
public static void main(String[] args) {
// Creating an object
MyClass obj = new MyClass("Database Connection");
// Dereference the object, making it eligible for GC
obj = null;
// Suggest garbage collection
System.gc();
// Wait for GC to finalize the object (not guaranteed to run immediately)
try {
Thread.sleep(2000); // Wait for garbage collection to happen
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Important Considerations:
- Resource Management: It is better to manage resources explicitly (e.g., using
try-with-resources
orAutoCloseable
interfaces) rather than relying onfinalize()
. The garbage collector’s timing is unpredictable, and relying on it for cleanup can lead to resource leaks. - Performance Impact: The garbage collection process can be slower if
finalize()
is used heavily, as it introduces extra work in object finalization.
Alternatives to finalize()
:
try-with-resources
: A cleaner and more reliable way to handle resource cleanup (for classes implementingAutoCloseable
).- Explicit Cleanup Methods: Manually calling cleanup methods for resources rather than relying on the garbage collector.
PhantomReference
andCleaner
: For more advanced and explicit resource management, Java providesPhantomReference
and theCleaner
API.
In conclusion, although finalize()
can be overridden to perform cleanup tasks, it is not recommended to use it in modern Java applications due to its unpredictability and deprecation in newer versions of Java.