Garbage collection
Finalization
Java technology allows you to use the finalize() method to do the necessary cleanup before the garbage collector removes the object from memory. This method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It is defined in the Object class, thus it is inherited by all classes. A subclass overrides the finalize() method to dispose of system resources or to perform other cleanup:
protected void finalize() throws Throwable
If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.
The finalize() method will be invoked only once in the lifetime of an object.
You can use an object's finalize() method to make it ineligible for garbage collection. Note, however, that the garbage collector will not run finalize() for this object again.
The finalize() method will always be invoked once before the object is garbage collected. However, the finalize() method might never be invoked for an object in its lifetime, because there is no guarantee that it will get garbage collected.
Note: we discussed the concept of garbage collection, which is the Java language's memory management technique. We saw that garbage collection cannot be forced. We also learned the different ways in which objects become eligible for garbage collection and that the finalize() method is invoked on an object before it is removed by the garbage collector.
No comments:
Post a Comment