Wednesday, March 14, 2012

Singleton pattern is tricky

1)  Singleton that every body knows
class Foo {
     private static Helper helper = null;     
     public static Helper getHelper() {         
     if (helper == null) { 
             helper = new Helper(); 
        }         
 return helper;
     }
    private Foo(){} 
}

Analyzing point 1: Pros: Good for single threaded application
Cons: Gets real bad in multithreaded programs. Ex: Threads 1,2 will start at the same time and create two instances defeating the purpose. Proof: try syso(getHelper());

2) Basic fix:
 
class Foo {
     private static Helper helper = null;     
     public static synchronized Helper getHelper() {         
     if (helper == null) { 
             helper = new Helper(); 
        }         
 return helper;
     }
    private Foo(){} 
}
Analyzing technique 2:
Pros: Wow!! fixes the cons of technique 1
Cons: Expensive. Imagine 50 Threads in your application and every time they invoke getHelper you pay the cost of synch and reduces application speed. 
3) Lazy Fix:
 
class Foo {
     private static Helper helper = new Foo();     
     public static Helper getHelper() {         
         return helper;
      }
    private Foo(){} 
}

Pros: Fixed it for MultiThreading. Loading static pieces once owned by class
Cons: UnNecessary creation of objects if not needed. Imagine you have a lot of classes with this fix and you want to create objects on meeting certain conditions, but this will all objects irrespective of conditions met

More techniques coming soon!!!