Tuesday 29 March 2016

Finalizer guardian

"Effective Java" Item 7: Avoid finalizer

In the last few paragraphs, a concept of 'Finalizer guardian' is introduced. It took me a while to get my head around it. So I would like to share my understanding.

When we override a class's finalize() method, it is important we call super.finalize(), because its super class may want to close some critical resources. However, people don't always remember to call super.finalize(). Here the finalizer guadian comes to rescue.

Let's have a look at an example. OK, here we forget to call super.finalize()

 public class FooSub extends Foo {  
   @Override  
   protected void finalize() throws Throwable {  
     System.out.println("FooSub garbage collected");  
   }  
 }  

But with finalizer Guardian, everything is still under control.

 public class Foo {  
   private CriticalResource criticalResource = new CriticalResource();  
   private final Object finalizerGuardian = new Object(){  
     @Override  
     protected void finalize() throws Throwable {  
       System.out.println("Critical resource closed");  
       criticalResource.close();  
     }  
   };  
   private static class CriticalResource implements Closeable{  
     public void close() throws IOException {  
     }  
   }  
 }  


 public static void main(String[] args) {  
     FooSub foo = new FooSub();  
     foo = null;  
     System.gc();  
   }  

Check the output

 Critical resource closed
 FooSub garbage collected 

No comments:

Post a Comment