Hello, Question to experienced Java programmers: How often in your practice you use finalize() to cleanup unused Java objects. I'm a little bit confused on this topic, since one of the strongest differnces from C++ was advertized to be garbage collector and promise to omit such pitfalls as memory leaks. But in Bruce Eckel's "Thinking in Java" book it's says, that Java takes care of all of the obects instantiated utilizing NEW statement. In all other cases cleanup is not guaranteed. So, basically memory leaks problem was resolved only partially in Java? So, the questions remains: how important and how often you guys use finalize() method or explicitly code Java Garbage collection routines. Thanks, --Alex
I think that you are confusing two separate topics. Java takes care of objects created with the new operator by using the garbage collector. There is nothing that you can do in Finalize that will CAUSE the cleanup of an object. Setting all references to the object to null is the only method that you have of trying to get rid of objects to prevent memory leaks (Yes you can explicitely call the gc() - but it is only a SUGGESTION that it should run now instead of later, not a command to make it run now). Once an object is cleaned up, any references that it held to other objects are gone without any need to specifically null them out in a finalize method, so why bother. Finalize gets invoked BY the garbage collector after it has ALREADY decided that it is time for this object to go. This is the place where you can specifically release any low-level (operating system level) resources that you may have that the gc does not know how to take care of, etc. So Finalize will in no way prevent memory leaks by objects. From the JLS
Finalizers provide a chance to free up resources that cannot be freed automatically by an automatic storage manager. In such situations, simply reclaiming the memory used by an object would not guarantee that the resources it held would be reclaimed.
Since I very seldom code classes that use such low level stuff (because I am an application programmer not a system programmer) I almost never have a need to have my own Finalize, and I just rely on the ones that Sun provides in it's classes. I do occasionally have cases where I know I am ABOUT to put a big strain on the system, and that while I am doing some time consuming I/O just ahead of that - this would be a good time for the gc() to run, so I go ahead and put in that suggestion.
"JavaRanch, where the deer and the Certified play" - David O'Meara