Tuesday 29 March 2016

Builder pattern

Quick template code

 public class FullName {  
   private final String firstName;  
   private final String lastName;  
   public static class Builder{  
     private String firstName;  
     private String lastName;  
     public Builder(){}  
     public Builder firstName(String firstName){  
       this.firstName = firstName;  
       return this;  
     }  
     public Builder lastName(String lastName){  
       this.lastName = lastName;  
       return this;  
     }  
     public FullName build(){  
       return new FullName(this);  
     }  
   }  
   private FullName(Builder builder) {  
     firstName = builder.firstName;  
     lastName = builder.lastName;  
   }  
 }  

Client code

 FullName name = new FullName.Builder().firstName("Ming").lastName("Sun").build();  

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