单例模式(Singleton)
来源:互联网 发布:sql server 2005序列号 编辑:程序博客网 时间:2024/06/15 01:23
- //饿汉式单例
public class HungerSingleton {
//类加载时直接创建实例
private static HungerSingleton instance = newHungerSingleton();
private HungerSingleton(){
}
public static HungerSingletongetInstance(){
return instance;
}
} - 懒汉式单例
public class LazySingleton {
private static LazySingleton instance =null;
privateLazySingleton(){
}
publicstatic LazySingleton getInstance(){
if (instance == null) {
instance = newLazySingleton();
}
return instance;
}
}
懒汉式单例在单线程下是安全的,但是在多线程下可能会是非安全的
1.Thread1 if(instance=null)为true且Thread2if(instance=null)也为true
这时会创建两个实例,改进方法就是加上(synchronized)同步机制:
public class LazySingleton {
private static LazySingleton instance =null;
privateLazySingleton(){
}
publicstatic synchronized LazySingleton getInstance(){
if (instance == null) {
instance = newLazySingleton();
}
return instance;
}
}
上例中同步机制能防止多线程下的非安全,但是会降低系统的效率,在服务器上为了顾及Singleton、LazyInitialization与效能问题
因而有了(双重检索锁定)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
0 0
- 单例模式(singleton)
- 单例(Singleton)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- Singleton(单例)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例(Singleton)模式
- 单例(Singleton)模式
- 单例(Singleton)模式
- 单例模式(Singleton)
- Singleton(单例模式)
- oracle常用网站
- Java代理模式(Proxy Design )
- 小东西,查看系统中程序开发清单
- 策略模式(Strategy)
- jdbc 总结
- 单例模式(Singleton)
- 客户端跳转与服务器跳转区别
- Java断言——assert(转自http://cnet…
- 输出结果显示百分比
- Ext.grid.ColumnModel设置
- js button
- iBatis2之SqlMap配置(转载…
- bat文件命令(摘自网络)
- oracle表连接详解