Java Reference
In-Depth Information
The “Goodbye” object is created on line 5 and assigned to the reference three . Then
three is set to null and the gc method is invoked. After line 7 the “Goodbye” object is
defi nitely eligible for garbage collection, but if the exam question asks you when the object
is garbage collected, the answer can only be “unknown.” The call to gc on line 8 might
have caused “Goodbye” to get garbage collected, but that is not guaranteed at all.
Line 9 does not cause “Hello” to become eligible because the reference two points to
“Hello” also. Only after line 11 does “Hello” become eligible for garbage collection, and
as already discussed we cannot know when the objects are actually garbage collected.
The finalize Method
According to the exam objectives, you need to be able to “recognize the behaviors of
the Object.finalize() method.” The garbage collector invokes the finalize method
of an object right before the object is actually garbage collected. The finalize method
is declared in Object , and any subclass can override finalize to perform any necessary
cleanup or dispose of system resources. The finalize method is only invoked on an object
once by the garbage collector.
There won't be any trick questions about finalize . Just remember it gets invoked once
and only when the object is in the process of being removed from memory. Be sure not
to do anything in the finalize method that might somehow cause the object's reference
to come back into scope. It is also a good idea to call super.finalize because you are
overriding the behavior of finalize in the parent classes.
Calling super.finalize
If you do call super.finalize , which is recommended, you need to declare the
java.lang.Throwable exception thrown by the parent class's finalize method:
public class A extends Object {
public void finalize() throws Throwable {
System.out.println(“Finalizing A”);
}
}
Let's look at an example. It is diffi cult to simulate garbage collection because you have little
control over the garbage collector, but I came up with an example that demonstrates when
the finalize method is called and also provides an extra level of complexity in
Search WWH ::




Custom Search