Control Flow  «Prev  Next»


Lesson 9Garbage collection and finalization
ObjectiveDescribe how the Java garbage collector uses finalization to allow objects to clean up after themselves.

Java Garbage Collection and Finalization

Finalization

The garbage collector invokes an object's finalize() method to allow the object to perform any completion processing, such as closing an open socket or disposing of a window, before the object is destroyed. When an object's finalize() method is invoked, it is possible for the object to become reachable again by assigning itself to a reachable program variable. Because of this possibility, the garbage collector does not immediately destroy an object after its finalize() method has completed. Instead, it waits until the next time that it has identified the object as unreachable.

Timeline for objects during Garbage Collection
Timeline for objects during Garbage Collection:
Finalization: Once an object's finalized() method is invoked, the object can clean up after itself, and potentially become reachable again.

Java Virtual Machine
Which option is true about compiling and running the following code?
class SuperTest{ 
 protected void finalize() { 
  super.finalize(); //1 
  System.out.println("SuperTest"); 
 } 
} 

public class Test extends SuperTest { 
 String s="abc"; 
 public static void main(String[] args) { 
  Test t=new Test(); //2 
  t.finalize(); //3 
 } 
}

Please select one option:
  1. Code will compile only if line 1 is removed.
  2. Code will compile only if line 3 is removed.
  3. Prints "SuperTest".
  4. Prints "SuperTest" only if garbage collector runs.
  5. Causes an exception to be thrown at runtime.
  6. None of the above.


Answer: a
Explanation:
Here the code will compile only if line 1 is removed. The super.finalize() method call invokes the finalize() method defined in the Object class. The finalize() method in the Object class throws Throwable, and since it is not handled at line 1, the code will not compile. There is no error in line 3. It is valid to invoke the finalize() method directly. If line 1 is removed, the code will compile and print "SuperTest".