- //饿汉式单例
public class HungerSingleton {
//类加载时直接创建实例
private static HungerSingleton instance = new HungerSingleton();
private HungerSingleton(){
}
public static HungerSingleton getInstance(){
return instance;
}
} - 懒汉式单例
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton(){
}
public static LazySingleton getInstance(){
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
懒汉式单例在单线程下是安全的,但是在多线程下可能会是非安全的
1.Thread1 if(instance=null)为true且Thread2 if(instance=null)也为true
这时会创建两个实例,改进方法就是加上(synchronized)同步机制:
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton(){
}
public static synchronized LazySingleton getInstance(){
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
上例中同步机制能防止多线程下的非安全,但是会降低系统的效率,在服务器上为了顾及Singleton、Lazy Initialization与效能问题
因而有了(双重检索锁定)Double-check Locking的模式,代码如下:
public class LazySingleton{
private static LazySingleton instance = null;
private LazySingleton(){
}
public static LazySingleton getInstance(){
if(instance==null){
//只有在第一次建立实例时才会进入同步区,之后由于实例已建立,也就不用进入同步区进行锁定。
synchronized (LazySingleton.class){
if (instance==null) {
instance =new LazySingleton();
}
}
}
return instance;
}
}
鉴于当前的内存模型的原因,该习语尚未得到广泛使用,就明显成为了一种不安全的编程结构。重定义脆弱的内存模型这一领域的工作正在进行中。尽管如此,即使是在新提议的内存模型中,双重检查锁定也是无效的。对此问题最佳的解决方案是接受同步或者使用一个 static field。
参考http://www.ibm.com/developerworks/cn/java/j-dcl.html
单例模式(Singleton)
最新推荐文章于 2025-03-16 17:08:38 发布
本文详细介绍了单例模式的两种实现方式:饿汉式和懒汉式,并深入探讨了懒汉式单例在多线程环境下的安全性问题及其解决办法。
1058

被折叠的 条评论
为什么被折叠?



