Java Reference
In-Depth Information
If it is still possible to have a memory leak, one might wonder if garbage collection really
bought us anything in Java and if it should be considered a good part of the language. It
doesn't take much thought to realize that the answer is still very much in the affirmative. Cases
like the one just shown where we are leaking memory are caused by local errors. In our ex-
ample, the local error was a failure to remove a reference from the collection when we were
done with that reference. This is much easier to find than memory leaks in non-garbage-col-
lected environments, where the problem is essentially global. Memory in such environments
is leaked when there is no place in the program where it is clear that the object is no longer
needed. This requires analyzing the entire program, a much more difficult job than tracking a
localized bug.
Other Resources
Although garbage collection frees the programmer from having to manage memory, there are
other resources that are used in a program that do require explicit management. File handles
and sockets, for example, are also scarce resources (their scarcity will depend on the under-
lying operating system) that will be used in a program and need to be freed once they are no
longer needed. Unlike memory, the Java environment does not help with the management of
such resources.
There are programmers who try to delegate the management of such resources to the garbage
collection system in Java. These attempts are usually done through the use of finalizers . In
almost all cases, such attempts are misguided at best and just wrong at worst. It's worth taking
a couple of minutes to talk about why.
A finalizer is a special method on a class that is run prior to any object of the class being
garbage collected. Such methods look like:
protected void finalize() throws Throwable{
Finalizers are the duals of constructors. Just as a constructor is run when an object is created, a
finalizer will be run when an object is about to be deleted by the garbage collector. You don't
have to call a finalizer for it to run (indeed, explicitly calling a finalizer is almost certainly a
mistake); that is taken care of by the garbage collection system.
Search WWH ::

Custom Search