V
vbhavsar
People have been coming up with creative solutions to lazily implement
the singleton pattern in a thread-safe way. We have seen things like
double-checked locking and creating instance via a single-elemnt enum
type.
I have thought of yet another way to implement this in a lazy and
thread-safe way. I haven't seen this proposed anywhere and it seems to
work unless I am missing something. Here it goes:
public class Singleton {
private static Singleton _instance;
private Singleton(){}
private synchronized static void createInstance(){
_instance = new Singleton();
}
public static Singleton getInstance(){
if (_instance == null){
createInstance();
}
return _instance;
}
}
The synchronized createInstance() method would eliminate the need to
do double-checked locking and the synchronization would happen only
when multiple threads call getInstance() before _instance has been
instantiated.
Anyone see any issues with this?
the singleton pattern in a thread-safe way. We have seen things like
double-checked locking and creating instance via a single-elemnt enum
type.
I have thought of yet another way to implement this in a lazy and
thread-safe way. I haven't seen this proposed anywhere and it seems to
work unless I am missing something. Here it goes:
public class Singleton {
private static Singleton _instance;
private Singleton(){}
private synchronized static void createInstance(){
_instance = new Singleton();
}
public static Singleton getInstance(){
if (_instance == null){
createInstance();
}
return _instance;
}
}
The synchronized createInstance() method would eliminate the need to
do double-checked locking and the synchronization would happen only
when multiple threads call getInstance() before _instance has been
instantiated.
Anyone see any issues with this?