博客
关于我
单例模式
阅读量:224 次
发布时间:2019-03-01

本文共 3591 字,大约阅读时间需要 11 分钟。

文章目录

1 饿汉式

/** * @author :wyaoyao * @date : 2020-04-06 14:32 * 单例模式:饿汉式 * 线程安全 * 但是在不使用的时候占用内存,因为通过static是类主动加载,不能能够懒加载 */public class SingletonSimple1 {       private static final SingletonSimple1 instance = new SingletonSimple1();    // 构造私有化。不允许外部调用    private SingletonSimple1() {       }    public static SingletonSimple1 getInstance() {           return instance;    }}
  • 线程安全
  • 但是在不使用的时候占用内存,通过static是类主动加载,不能能够懒加载

测试

// 测试@Testpublic void test() {       SingletonSimple1 instance1 = SingletonSimple1.getInstance();    SingletonSimple1 instance2 = SingletonSimple1.getInstance();    Assert.assertTrue(instance1 == instance2);}

懒汉式

/** * @author :wyaoyao * @date : 2020-04-06 14:41 * 饿汉式:懒加载 */public class SingletonSimple2 {       private static SingletonSimple2 instance;    private SingletonSimple2(){       }    // 存在线程安全问题    public static SingletonSimple2 getInstance(){           if(null == instance){               instance = new SingletonSimple2();        }        return instance;    }}
  • 这个懒加载,在使用的时候才会创建对象,但是线程不安全

测试

// 测试,构建100线程去创建对象,测试是否线程安全@Testpublic void test2() {       for (int i = 0; i<100; i++){           new Thread(()->{               SingletonSimple2 instance = SingletonSimple2.getInstance();            System.out.println(instance);        },"T"+i).start();    }    /**     * 不安全,并不是单例的,SingletonSimple2@608f35ee,SingletonSimple2@5617e729     * study.wyy.concurrency.designpatterns.singleton.SingletonSimple2@608f35ee     * study.wyy.concurrency.designpatterns.singleton.SingletonSimple2@5617e729     * study.wyy.concurrency.designpatterns.singleton.SingletonSimple2@7df5ed4e     * study.wyy.concurrency.designpatterns.singleton.SingletonSimple2@7df5ed4e     * study.wyy.concurrency.designpatterns.singleton.SingletonSimple2@7df5ed4e     */}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jSHdx6qg-1599738853607)(evernotecid://FA2713E9-40BE-49E5-BF9D-E3ACD77E4128/appyinxiangcom/21741088/ENResource/p542)]

解决懒汉式的线程不安全

方案一

// 加锁    public synchronized static SingletonSimple2 getInstance(){           if(null == instance){               instance = new SingletonSimple2();        }        return instance;    }

问题

  • 除了第一次是创建,以后都是读的操作,每次都会加锁,效率不高

方案二

double check

public class SingletonSimple3 {       private static SingletonSimple3 instance;    private SingletonSimple3(){       }    public static  SingletonSimple3 getInstance(){           if(null == instance){               synchronized (SingletonSimple3.class){                   if(null == instance){                       instance = new SingletonSimple3();                }            }        }        return SingletonSimple3.instance;    }}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D4qVca7W-1599738853614)(evernotecid://FA2713E9-40BE-49E5-BF9D-E3ACD77E4128/appyinxiangcom/21741088/ENResource/p543)]

也存在问题:可能会引起npe

解决这个问题很简单,使用volatile关键字即可

public class SingletonSimple3 {       private static volatile SingletonSimple3 instance;    private SingletonSimple3(){       }    public static  SingletonSimple3 getInstance(){           if(null == instance){               synchronized (SingletonSimple3.class){                   if(null == instance){                       instance = new SingletonSimple3();                }            }        }        return SingletonSimple3.instance;    }}

ClassHolder

  • 支持懒加载
  • 线程安全
  • 不会npe
public class SingletonSimple5 {       private SingletonSimple5(){       }    private static class InstanceHolder {           private final static SingletonSimple5 instance = new SingletonSimple5();    }    public static SingletonSimple5 getInstance(){           return InstanceHolder.instance;    }}

枚举方式

转载地址:http://obrv.baihongyu.com/

你可能感兴趣的文章
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>