Monday, April 13, 2009

Singleton without "synchronized" keyword in Multi-Threaded App

When you ask a designer or developer to write a multi-threaded application, in their mind, the magic word - 'synchronized' immediately pops-up! That was my mentality as well until I came across this wonderful website explaining the different design patterns. It hit me hard. You can check it on this link http://www.oodesign.com/singleton-pattern.html.

Typical Singleton object looks like this:

//This is bad. The whole method is synchronized. If your method has
//thousands of lines of code then you are creating a bottleneck here... 
public class MySingletonObject{
private static MySingletonObject instance;

private MySingletonObject(){}

public synchronized static MySingletonObject  getInstance(){
if(instance==null){
instance = new MySingletonObject();
}
return instance;
}
}

or

//This is better. Only the block of instantiation is synchronized. But....
//There's always this null check overhead. Also, you still have the 
//synchronized keyword. It's still an overhead.
public class MySingletonObject{
private static MySingletonObject instance;

private MySingletonObject(){}

public static MySingletonObject  getInstance(){
synchronized(MySingletonObject .class){
if(instance==null){
instance = new MySingletonObject();
}
}
return instance;
}
}

//This is what you want. What? Why?...... Never underestimate
//the power of static modifier. Once you call this class
//say MySingletonObject.getInstance(), the classloader will automatically load
//and create the instance of MySingletonObject type.
//This member variable only has 1 instance all throughout the application
//since its at the class level. No more bottlenecks. No more waiting for the
//threads. They immediately get an instance. Looks very simple too...

public class MySingletonObject{
private static MySingletonObject instance = new MySingletonObject();

private MySingletonObject(){}

public static MySingletonObject  getInstance(){
return instance;
}
}

1 comment:

  1. Great blog i never see before. Thank you for this blog. 

    PIC Scheme

    ReplyDelete