美文网首页
单例模式

单例模式

作者: Green_Apple | 来源:发表于2017-08-10 16:39 被阅读0次

1、懒汉式(线程并不安全)

public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
}
2、懒汉式(线程安全)
由于是对方法进行synchronized 故效率十分低下
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
}
3、饿汉式(线程安全)
把初始化操作交给类加载器,但没有延迟加载的效果,效果一般
public class Singleton {
private static Singleton instance=new Singleton();
private Singleton(){}
public static synchronized Singleton getInstance(){
return instance;
}
}
4、双重校验锁(线程不安全)
该方式其实是对懒汉式的一个改进,使其延迟初始化,减少同步的开销

public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null)
synchronized(Singleton.class){
if(instance==null)
instance=new Singleton();
}
return instance;
}
}
该方式不是线程安全的原因是:不同步情况下,对引用类型是不安全的。
举例:若有线程A进入synchronized中 执行构造函数,但构造函数未执行完毕
线程B则在第一个instance 时可见,判断是instance则不为null 反回了部分
初始化的instance,从而导致校验模式的失败
使用volatile 保证顺序的一致性(线程安全)
public class Singleton {
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null)
synchronized(Singleton.class){
if(instance==null)
instance=new Singleton();
}
return instance;
}
}
推荐方式 IODH :Initialization on Demand Holder
(线程安全且效率高,性能好)
public class Singleton {
private Singleton(){}
static class SingletonHolder{
static final Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
文档解释:
https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom

大概意思是:
类是由JVM加载的,类的初始化。
类没有任何静态变量进行初始化,所以静态类定义SingletonHolder内也
没有被初始化。直到JVM确认SingletonHolder必须被执行,并且是第一次
发生时才会被初始化,又是因为内部类,导致静态变量INSTANCE是被外层
类的构造函数进行初始化,该初始化阶段是由JLS保证串行,即非并发,因此在加载和初始化期间,静态getInstance方法中不需要进一步的同步。并且由于初始化阶段在串行操作中写入静态变量INSTANCE。
虽然实现是一个高效的线程安全的“单例”缓存,没有同步开销,并且性能比无限制的同步性能好,只有当Something的构造可以保证不失败
时,成语才能使用。在大多数JVM实现中,如果Singleton的
构造失败,则从同一个类加载器初始化它的后续尝试将导致
NoClassDefFoundError失败

相关文章

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

  • java的单例模式

    饿汉单例模式 懒汉单例模式

网友评论

      本文标题:单例模式

      本文链接:https://www.haomeiwen.com/subject/ouphrxtx.html