下面的getInstance()方法有什么问题 [英] What's wrong with the following getInstance() method
问题描述
我一直在学习求职面试,我发现这个问题:
I've been studying for a job interview and I've found this question:
下面的Singleton工厂方法getInstance()有什么问题?
What's wrong with the following Singleton factory method getInstance()?
public class Singleton {
private static Singleton mySingleton;
protected Singleton() {}
public static Singleton getInstance() {
if (mySingleton == null) {
synchronized(Singleton.class) {
if(mySingleton == null) {
mySingleton = new Singleton();
}
}
}
return mySingleton
}
}
我知道构造函数是错误的,应该是私有的。但是,他们问的是getInstance()方法有什么问题,一切对我看起来不错,我看过很多这样的例子(在多线程环境中)我缺少什么?
I know the constructor is wrong and should be private. However, they're asking about what's wrong with the getInstance() method, everything looks fine to me, I've seen a lot of examples like this one (in a multithreading environement) what am I missing?
推荐答案
原始代码最大的问题是它是反复检查反模式的典型示例。它看起来不错,但只是坏了。更多相关信息:
http://www.cs .umd.edu /〜pugh / java / memoryModel / DoubleCheckedLocking.html
The largest problem with the original code is that it is a classic example of the Double Check anti-pattern. It looks great but is just broken. More on that here: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
请注意,从Java 1.5开始,模式或更好的静态初始化真的是走的路。
Note that as of java 1.5 there is a way to finesse it, the synchronized pattern or better static initialization is really the way to go.
-edit
(我只是注意到这是一个求职面试,如果他们显示这个例子,对于细节,我会去与复杂的java内存问题,你没有完全理解,但接受事实,以避免双重检查。
这篇关于下面的getInstance()方法有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!