Safe Singleton for your multi-core servers

Purpose of a Singleton is to have one copy of an object in JVM. But writing below code without volatile in a multi core environment may result in multiple copies of Singleton if any failover occurs.
In a multi-core server multiple Threads of your code may try to create a Singleton object. If singleton variable ( _instance ) is properly not visible to all Threads in all running conditions then Singleton will appear with multiple copies ( which is never expected ).To avoid such cases _instance variable should be declared volatile to make sure if a Thread is creating Singleton instance and just after creation it lost the CPU, all other threads should be communicated that _instance is not null now.

public class Singleton{

private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
} 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s