Java Reference
In-Depth Information
21. System.gc();
22. System.out.println(“End of main...”);
23.
24. }
25. }
The calls to
gc
are an attempt to force garbage collection so we can see when
finalize
is invoked on the
Dog
objects. The fi rst step is determining when the objects are eligible for
garbage collection. Adding the two
Dog
objects to the
Vector
creates additional references
to the objects. On line 11 the reference
one
is set to
null
, but
Snoopy
is not eligible yet for
garbage collection because of line 8. The
Vector
still has a reference to the Snoopy object,
as shown in Figure 1.10.
FIGURE 1.10
The
Vector
still has a reference to the
Snoopy
object.
one
null
“Snoopy”
10
two
vector
0
1
Vector<Dog> object
“Lassie”
12
However, when you set
vector
to
null
on line 15, it causes the
Snoopy
object to
immediately become eligible for garbage collection. The
Lassie
object still has the
reference
two
pointing to it, so it does not become eligible until after line 19. Here is a
sample output of the
GCDemo3
program. (I use the term “sample output” because the output
can change each time the program is executed depending on when the garbage collector
actually invokes the
finalize
method.)
Calling gc once...
Calling gc twice...
Snoopy is being garbage collected
Calling gc again...
Lassie is being garbage collected
End of main...
Search WWH ::
Custom Search