« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9694049 建立时间:2004年12月20日 |

| |
[编程感想]Singleton pattern, Double-checked Locking pattern出现的问题  原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2007/7/4 13:03:42 |
最近研究设计模式,发现一个问题,最初的Singleton pattern是这样写的,class Singleton{ private static Singleton instance = new Singleton(); public instance() { return instance; }//...}后来很多程序员发现延时加载更好,这样不在类的加载时浪费时间,于是改为class Singleton { private static Singleton instance = null; public static instance() { if( instance == null ) { instance = new Singleton(); } return instance; }
}出现了线程问题,又改为static Singleton instance;
public static synchronized Singleton getInstance() { if (instance == null) instance == new Singleton(); return instance;}其实这段代码是很好的,看过Design Pattern java work book的人会说,package com.oozinoz.machine;public class Factory_2 { private static Factory_2 factory; private static final Object classLock = Factory_2.class;
public static Factory_2 getFactory() { synchronized (classLock) { if (factory == null) { factory = new Factory_2(); } return factory; } } 同步代码块比同步方法代价小很多啊,其实这段代码有问题,这本书介绍的是错误的,这就是著名的Double-Checked Locking (DCL)问题。无论你通过何种手段,在JVM hotspot 1.5之前,你是解决不了这个问题的, Effective Java 在item 48也会说明了这个问题。java5使用volatile可以解决这个问题,public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance;}静态初始化,static class SingletonHolder { static Singleton instance = new Singleton(); }
public static Singleton getInstance() { return SingletonHolder.instance;} 静态方法一旦类初始化失败,类就不可能使用,而且难于debug,出现ClassNotFoundException异常会有问题的,不建议使用。大家看sixsun的blog有DCL问题的说明 http://blogger.org.cn/blog/more.asp?name=sixsun&id=9312 |
|
|