Java Reference
In-Depth Information
Java's garbage collection system reclaims objects automatically—occurring transpar-
ently, behind the scenes, without any programmer intervention. It works like this: When no
references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object is released. This recycled memory can then be used for a subsequent
allocation.
Ask the Expert
Q :
Why don't I need to use new for variables of the primitive types, such as int or
float?
A : Java's primitive types are not implemented as objects. Rather, because of efficiency
concerns, they are implemented as “normal” variables. A variable of a primitive type
actually contains the value that you have given it. As explained, object variables are
references to the object. This layer of indirection (and other object features) adds
overhead to an object that is avoided by a primitive type.
Garbage collection occurs only sporadically during the execution of your program. It
will not occur simply because one or more objects exist that are no longer used. For effi-
ciency, the garbage collector will usually run only when two conditions are met: there are
objects to recycle, and there is a need to recycle them. Remember, garbage collection takes
time, so the Java run-time system does it only when it is appropriate. Thus, you can't know
precisely when garbage collection will take place.
The finalize( ) Method
It is possible to define a method that will be called just before an object's final destruction
by the garbage collector. This method is called finalize( ) , and it can be used to ensure that
an object terminates cleanly. For example, you might use finalize( ) to make sure that an
open file owned by that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run-time
system calls that method whenever it is about to recycle an object of that class. Inside the
finalize( ) method, you will specify those actions that must be performed before an object
is destroyed.
The finalize( ) method has this general form:
Search WWH ::




Custom Search