关于 Java 单例模式的 Synchronized 的用法

2015-12-10 11:38:11 +08:00
 Totato5749
  1. public static Singleton getInstance() {
  2. if (instance == null) {
  3. synchronized (Singleton.class) {
  4. if (instance == null) {
  5. instance = new Singleton();
  6. }
  7. }
  8. }
  9. return instance;
  10. }

我发现网上单例模式中 getInstance 方法基本上都是这么写的,我觉得这种写法虽然正确但是一点都不易读。 请教各位,像我下面这样写正确吗?

public static synchronized Singleton getInstance(){
if(mInstance == null){
mInstance = new Singleton();
}
return mInstance;
}

2638 次点击
所在节点    问与答
15 条回复
rails3
2015-12-10 11:46:33 +08:00
最好的静态内部类
zhaohui318
2015-12-10 11:50:08 +08:00
经典案例啊,你这个性能要差很多
zts1993
2015-12-10 11:51:29 +08:00
第一种 如果不为空 不用加锁,,你这个,自己没看出问题么。。。。
xufang
2015-12-10 12:01:16 +08:00
neo2015
2015-12-10 12:05:45 +08:00
public synchronized static Singleton getInstance(){
if(mInstance == null){
mInstance = new Singleton();
}
return mInstance;
}

private static class SingletonInstance{

}
sun2920989
2015-12-10 12:07:20 +08:00
你的写法理论上说没问题 但是并发访问的时候不如第一种效率高 单例的东西 永远是需要生成的时候少 已经存在的时候多
neo2015
2015-12-10 12:08:11 +08:00
public synchronized static Singleton getInstance(){
if(mInstance == null){
mInstance = SingletonInstanc.mInstance
}
return mInstance;
}

private static class SingletonInstance{
private static Signleton mInstance = new Singleton()
}
SparkMan
2015-12-10 12:43:34 +08:00
现在更流行用 enum 类型,比 double check 还牛逼
pixstone
2015-12-10 12:52:32 +08:00
public static synchronized Singleton getInstance(){ 取方法的时候上锁。。。。这效率要多低啊。。。合理的上锁模式是 实例化的时候上锁 防止重复实例。
baozijun
2015-12-10 12:54:10 +08:00
你这个每次获取对象时都是加锁的,效率非常低.上面的那个有对象直接返回,没有才加锁,然后判断 此时对象的状态 是否为空,空的话创建
zouxcs
2015-12-10 13:12:22 +08:00
静态内部类整一个
Totato5749
2015-12-10 13:39:11 +08:00
谢谢诸君,学到了很多。
ganxiyun
2015-12-10 14:19:28 +08:00
我觉得楼主贴的 DCL 好像 java 不适用吧,难道现在可以这么用了?
ganxiyun
2015-12-10 14:20:34 +08:00
DCL 不是用

// Works with acquire/release semantics for volatile
// Broken under Java 1.4 and earlier semantics for volatile
class Foo {
private volatile Helper helper;
public Helper getHelper() {
Helper result = helper;
if (result == null) {
synchronized(this) {
result = helper;
if (result == null) {
helper = result = new Helper();
}
}
}
return result;
}

// other functions and members...
}
unique
2015-12-10 14:44:13 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/242484

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX