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...
//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.
//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...
//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;
}
}
No comments:
Post a Comment