Java Reference
In-Depth Information
This shows that the invocation of
printThree
in the constructor for class
Super
does
not invoke the definition of
printThree
in class
Super
, but rather invokes the overriding
definition of
printThree
in class
Test
. This method therefore runs before the field initial-
izers of
Test
have been executed, which is why the first value output is
0
, the default
value to which the field
three
of
Test
is initialized. The later invocation of
printThree
in
method
main
invokes the same definition of
printThree
, but by that point the initializer
for instance variable
three
has been executed, and so the value
3
is printed.
12.6. Finalization of Class Instances
The class
Object
has a
protected
method called
finalize
; this method can be overridden by other
classes. The particular definition of
finalize
that can be invoked for an object is called the
finalizer
of that object. Before the storage for an object is reclaimed by the garbage collect-
or, the Java Virtual Machine will invoke the finalizer of that object.
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.
The Java programming language does not specify how soon a finalizer will be invoked, ex-
cept to say that it will happen before the storage for the object is reused.
The Java programming language does not specify which thread will invoke the finalizer for
any given object.
It is important to note that many finalizer threads may be active (this is sometimes
needed on large shared memory multiprocessors), and that if a large connected data
structure becomes garbage, all of the
finalize
methods for every object in that data
structure could be invoked at the same time, each finalizer invocation running in a
different thread.
The Java programming language imposes no ordering on
finalize
method calls. Finalizers
may be called in any order, or even concurrently.
As an example, if a circularly linked group of unfinalized objects becomes unreach-
able (or finalizer-reachable), then all the objects may become finalizable together.
Eventually, the finalizers for these objects may be invoked, in any order, or even con-
currently using multiple threads. If the automatic storage manager later finds that the
objects are unreachable, then their storage can be reclaimed.