线程安全的单例模式
来源:互联网 发布:数据库数据如何查找 编辑:程序博客网 时间:2024/06/06 09:19
1、饿汉式单例
public class Singleton { private final static Singleton INSTANCE = new Singleton(); private Singleton() { } public static Singleton getInstance() { return INSTANCE; }}2、借助内部类
属于懒汉式单例,因为Java机制规定,内部类SingletonHolder只有在getInstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。
public class Singleton { private Singleton() { } private static class SingletonHolder { private final static Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; }}3、普通加锁解决
public class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; }}虽然解决了线程安全问题,但是每个线程调用getInstance都要加锁,我们想要只在第一次调用getInstance时加锁,请看下面的双重检测方案
4、双重检测,但要注意写法
public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronzied(Singleton.class) { Singleton temp = instance; if(temp == null) { temp = new Singleton(); instance = temp } } } return instance; }}由于指令重排序问题,所以不可以直接写成下面这样:public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronzied(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; }}但是如果instance实例变量用volatile修饰就可以了,volatile修饰的话就可以确保instance = new Singleton();对应的指令不会重排序,如下的单例代码也是线程安全的:public class Singleton { private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronzied(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; }}
0 0
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- Volatile 线程安全的单例模式
- 线程安全的单例模式
- 基于线程安全的单例模式
- 线程安全的单例模式
- 单例模式的线程安全
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式 [老生常谈]
- java线程安全的单例模式
- 线程安全的单例模式
- + 线程安全的单例模式
- 归并排序
- LA 3602 DNA 序列 模拟
- tomcat服务器分包
- 字符串转数字
- 使用 Android Studio 进行 NDK 开发
- 线程安全的单例模式
- ZOJ 3870 本篇文章转载自——白羊_baiyang
- 免费的论文查重网站
- Python使用traceback.print_exc()来代替print e 来输出详细的异常信息
- Expression is not assignable
- 计算四棱柱的表面积与体积
- 九度 1017
- Android系列之网络(二)----HTTP请求头与响应头
- Java基础知识精华