Thursday, October 18, 2007

Finalizer guardian Idiom

Finalizer Guardian idiom is nothing but an anonymous class assigned to a private final instance variable within a class that wants to override the finalize method .

The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :

public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}

Little Sugar (Handling Exceptions in Finalize )

Lets consider a scenario where you have a class A and a subclass of that class called B.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.

So your implementation should look like this :

protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}

}

That way ,
any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.

Little Sugar (Java Finalization )

Uncaught exceptions thrown in the finalize method of an object are not caught . Infact they cause the finalization process to terminate and leave the object in a corrupt state . Now that's weird ...

So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .