单例模式和双检测的加锁(Double-checked locking and the Singleton pattern)
?单例模式在编程中很常见。当多个线程使用时,必须使用某种类型的同步。为了使你的代码更高效,Java程序员在单例模式中使用双重检测锁定来限制并发执行的代码量。但是,由于Java内存模型的一些鲜为人知的细节,这种双重检查锁定是不能保证工作,它会偶尔失败。此外,其失败的原因并不明显,涉及到Java内存模型的内部细节。并且是很难追查的。在本文的其余部分,我们将仔细研究双重检查锁定了解它什么时候就发生了。
单例模式的习惯写法
Listing1
?
public static Singleton getInstance(){ if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 inst = new Singleton(); //4 } instance = inst; //5 } } } return instance;}?改进的地方就是将构造方法的调用和赋值分开来写,只在调用构造方法中加锁,就是new的时候。后续参见
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
?
?