This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Finalization Is Less Predictable
Posted by Bill Venners on 13 Jan 1999, 1:49 PM
> The trick to release non-memory resources in a destructor in C++
> seems not to apply anymore in Java, because garbage collection
> and finalization is not as controlled. Do you agree? Of course,
> may be someone could argue that it has never been an excellent
> idea in C++ to do so, but it is cleaner because C++ does not
> have a finally clause.
Finalization is not as predicatable as destruction, which is why
explicit call to a cleanup method is necessary in Java to
release non-memory finite resources.
> Given the behavior in Java, we almost always have to provide a
> seperate method to release resources, and make sure that the
> method is called at the right time instead of relying on the
> finalizer to do so.
> It also seems that we almost always want to call System.runFinalizersOnExit(true) such that objects will be guaranteed to be finalized no matter how the program
> ends. Am I right?
Well, only if the resource you are releasing won't be freed up
anyway when the program exits. If you have an open file, for
example, and your program just quits without explicitly closing
the file, it doesn't usually matter. If your program had the
file locked, the OS will usually release the lock if your
program dies without explicitly releasing the lock.