
Garbage Collector (GC) reclaims memory occupied by objects that are no longer in use by the program. GC calls object’s finalize() method to perform clean up operations before the object is removed from the memory.
Following code shows how finalize() method is implemented in a class.
public class FinalizerClass {
FileInputStream fis;
@Override
protected void finalize() throws Throwable {
try {
if (fis != null) {
fis.close();
fis = null;
}
} finally {
super.finalize();
}
}
}
This sample code shows how finalize() method can be used to release a file handle. However it is not recommended to use finalize() methods to release non memory resources like file handles, sockets, database connections. Because, there is no guarantee that GC runs immediately when an object becomes unreachable.
Non memory resources like file handles, sockets, database connections are limited resources. Java can allocate only a finite number of these resources, so they should be released immediately when we have finished with them. It might take hours for GC to run. If we depend on GC to release these finite resources, application might fail.
A better approach would be to create a public close method for FinalizerClass and call this method from clients.
public class FinalizerClass {
FileInputStream fis;
public void close() throws IOException {
if (fis != null) {
fis.close();
fis = null;
}
}
}
class Client {
FinalizerClass fc = new FinalizerClass();
public void foo() throws IOException {
try {
// do something with fc
} finally {
fc.close();
}
}
}
Note 1: Non memory resources like file handles, sockets are not managed by JVM, rather they are managed by the operating system. Therefore you should call close() method of these resources in your code.
Note 2: If you are using Java 7 or later, you can also use try-with-resources Statement and AutoCloseable objects.
Related Subjects
Garbage Collector
Object Finalization
Reference Types
AutoCloseable Interface