线程安全方法
我目前有一个实现单例设计模式的程序:
public class Singleton {
private static Singleton s;
private Singleton(){
}
public static Singleton getInstance(){
if(s == null){
s = new Singleton();
}
return s;
}
}
在一次采访中有人问我,给定这样的程序,有哪些好的选择可以使 getInstance 方法线程安全。我知道一种方法就是在方法之前标记synchronized,但是面试官说还有其他更有效的方法来处理使方法线程安全的问题。
任何人都可以提供任何想法吗?
I currently have a program implementing a Singleton design pattern:
public class Singleton {
private static Singleton s;
private Singleton(){
}
public static Singleton getInstance(){
if(s == null){
s = new Singleton();
}
return s;
}
}
I was asked in an interview that given a program like this, what are some good options to make the getInstance method thread safe. I know that one method is just to tag synchronized before the method, but the interviewer said there were other more efficient ways to deal with making methods thread safe.
Can anyone offer any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我至少能想到三个,尽管其中两个可以归结为相同的原理。
基本上,您可以让类加载器担心线程安全,或者从 Java5 开始使用双重检查锁定。
第一个版本意味着拥有一个包含实际代码的内部类/枚举,第二个版本意味着您使 Singleton 实例可变并使用通常的 if-synchronize-if 解决方案。
At least three I can think of, although two of those boil down to the same principle.
Basically you can either let the classloader worry about thread-safety or use double-checked locking from Java5 onwards.
The first versions means having an inner class/enum that contains the actual code, the second that you make the Singleton instance volatile and use the usual if-synchronize-if solution.
哦,我的话,不会再这样了。
编写此代码的最佳方法是最简单的:
使 getter 同步是第二好的方法。有一些更复杂的方法可以做到这一点,但它们都不值得付出努力 -
synchronized
非常便宜,并且不要让任何人告诉您其他情况。Oh my word, not this again.
The very best way to write this is the simplest:
Making the getter synchronized is the second best. There are a few more complex ways to do it, but none of them are worth the effort --
synchronized
is very cheap, and don't let anyone tell you otherwise.1.在类加载时创建实例变量。
优点:
缺点:
2.同步getInstance()方法
优点:
缺点:
3.在if循环和易失性变量中使用synchronized块
优点:
缺点:
1.Create the instance variable at the time of class loading.
Pros:
Cons:
2.Synchronize the getInstance() method
Pros:
Cons:
3.Use synchronized block inside the if loop and volatile variable
Pros:
Cons: