Java Reference
In-Depth Information
There are some important threading issues here: the instance variable must be declared
volatile , and there is a slight performance benefit in assigning the instance variable to a
local variable. More details of that are given in Chapter 9 ; in the occasional case where lazy
initialization of threaded code makes sense, this is the design pattern to follow.
Eager deinitialization
The corollary to lazily initializing variables is eagerly deinitializing them by setting their
value to null . That allows the object in question to be collected more quickly by the garbage
collector. While that sounds like a good thing in theory, it is really useful only in limited cir-
A variable that is a candidate for lazy initialization might seem like a candidate for eager
deinitialization: in the examples above, the Calendar and DateFormat objects could be set
to null upon completion of the report() method. However, if the variable isn't going to be
used in subsequent invocations of the method (or elsewhere in the class), there is no reason
to make it an instance variable in the first place: simply create the local variable in the meth-
od, and when the method completes, the local variable will fall out of scope and the garbage
collector can free it.
The common exception to the rule about not needing to eagerly deinitialize variables occurs
with classes like those in the Java collection framework: classes that hold references to data
for a long time, and then are informed that the data in question is no longer needed. Consider
the implementation of the remove() method in the ArrayList class of the JDK (some code
public E remove ( int
int index ) {
E oldValue = elementData ( index );
int numMoved = size - index - 1 ;
iif ( numMoved > 0 )
System . arraycopy ( elementData , index + 1 ,
elementData , index , numMoved );
elementData [-- size ] = null
null ; // clear to let GC do its work
return oldValue ;
The code comment about GC appears in the (otherwise sparsely commented) JDK source it-
self: setting the value of a variable to null like that is an unusual enough operation that some
explanation is needed. In this case, trace through what happens when the last element of the
array is removed. The number of items remaining in the array—the size instance vari-
Search WWH ::

Custom Search