Clearing resources
Alternatives to finalize() for clearing an object’s memory resources?
Q: How dependable is the finalize() method to clean all of the resources used by an object? Are there any different and more dependable methods for clearing the resources?
A:
If a program never comes up short of memory, though, the garbage collector might not run at all, so the finalizers would never execute. This means that finalizers shouldn’t be used to free nonmemory resources like file descriptors or database connections. A well-designed class should include methods to explicitly free any such resources it allocates. A well-designed program will ensure these methods are called as soon as the resources are no longer necessary.
Bill Venners’s Design Techniques column, “Object finalization and cleanup,” covers this topic in detail (see Resources). The only point we could add to Bill’s article is a discussion of the dangers of runFinalizersOnExit()
, a method of java.lang.Runtime
. Some developers use this method to ensure that every object’s finalize()
method will be called before the Java program exits. Unfortunately, it sometimes causes an object’s finalize()
method to be called before the object has been garbage collected!
Considering the potential dangers, you should at all costs refrain from using the poorly implemented runFinalizersOnExit()
method.