How below 2 codes are different in terms of multithreaded environment?
Code 1:
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
pub开发者_JS百科lic static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Code 2:
class Singleton {
private static Singleton uniqueInstance;
private Singleton() { ... }
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
Why Code 2 will not work in multi threaded environment, when it has also static variable declared which will get loaded once class is loaded & thus it'll have only one instance?
Thanks!
Remember that more than one thread can call getInstance
at a given time.
In Example 1, the initializer for the uniqueInstance
member is guaranteed to be only run once - at class load time.
In Example 2, since initialization takes place inline in getInstance
, more than one thread can independently and concurrently find the uniqueInstance
member variable to be null
. Each thread will then call new Singleton()
, with indeterminate results that depend on the timing of the two (or more) threads.
For Example 2 to work, you could (for example) add synchronized
on the getInstance
method.
Your comment about the variable being fully initialized at class load time is true for Example 1, but not for 2 - in example 2 the member variable is set to null
at class load time, but populated with an object instance later, during the first call(s) to getInstance
.
Multiple threads may be inside of the:
if (uniqueInstance == null) {
...
}
condition simultaneously.
精彩评论