Java单例模式的8种写法(推荐)
作者:Zerone Wong 发布时间:2023-01-06 14:23:27
单例:Singleton,是指仅仅被实例化一次的类。
饿汉单例设计模式
一、饿汉设计模式
public class SingletonHungry {
private final static SingletonHungry INSTANCE = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstance() {
return INSTANCE;
}
}
因为单例对象一开始就初始化了,不会出现线程安全的问题。
PS:因为我们只需要初始化1次,所以给INSTANCE加了final
关键字,表明初始化1次后不再允许初始化。
懒汉单例设计模式
二、简单懒汉设计模式
由于饿汉模式一开始就初始化好了,但如果一直没有被使用到的话,是会浪费珍贵的内存资源的,所以引出了懒汉模式。
懒汉:首次使用时才会去实例化对象。
public class SingletonLazy1 {
private static SingletonLazy1 instance;
private SingletonLazy1() {
}
public static SingletonLazy1 getInstance() {
if (instance == null) {
instance = new SingletonLazy1();
}
return instance;
}
}
测试:
public class Main {
public static void main(String[] args) {
SingletonLazy1 instance1 = SingletonLazy1.getInstance();
SingletonLazy1 instance2 = SingletonLazy1.getInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
测试结果:从结果可以看出,打印出来的两个实例对象地址是一样的,所以认为是只创建了一个对象。
三、进阶
1:解决多线程并发问题
上述代码存在的问题:在多线程环境下,不能保证只创建一个实例,我们进行问题的重现:
public class Main {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
}
}
结果:获取到的对象不一样,这并不是我们的预期结果。
解决方案:
public class SingletonLazy2 {
private static SingletonLazy2 instance;
private SingletonLazy2() {
}
//在方法加synchronized修饰符
public static synchronized SingletonLazy2 getInstance() {
if (instance == null) {
instance = new SingletonLazy2();
}
return instance;
}
}
测试:
public class Main2 {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
}
}
结果:多线程环境下获取到的是同个对象。
四、进阶2:缩小方法锁粒度
上一方案虽然解决了多线程问题,但由于synchronized关键字是加在方法上的,锁粒度很大,当有上万甚至更多的线程同时访问时,都被拦在了方法外,大大降低了程序性能,所以我们要适当缩小锁粒度,控制锁的范围在代码块上。
public class SingletonLazy3 {
private static SingletonLazy3 instance;
private SingletonLazy3() {
}
public static SingletonLazy3 getInstance() {
//代码块1:不要在if外加锁,不然和锁方法没什么区别
if (instance == null) {
//代码块2:加锁,将方法锁改为锁代码块
synchronized (SingletonLazy3.class) {
//代码块3
instance = new SingletonLazy3();
}
}
return instance;
}
}
测试:
public class Main3 {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
}
}
我们看一下运行结果:还是出现了线程安全的问题(每次执行都可能打印不同的地址情况,只要证明是非线程安全的即可)。
原因分析:当线程A拿到锁进入到
代码块3
并且还没有创建完实例时,线程B是有机会到达代码块2
的,此时线程C和D可能在代码块1
,当线程A执行完之后释放锁并返回对象1,线程B进入进入代码块3
,又创建了新的对象2覆盖对象1并返回,最后当线程C和D在进行判null时发现instance非空,直接返回最后创建的对象2。
五、进阶3:双重检查锁DCL(Double-Checked-Locking)
所谓双重检查锁,就是在线程获取到锁之后再对实例进行第2次判空检查,判断是不是有上一个线程已经进行了实例化,有的话直接返回即可,否则进行实例初始化。
public class SingletonLazy4DCL {
private static SingletonLazy4DCL instance;
private SingletonLazy4DCL() {
}
public static SingletonLazy4DCL getInstance() {
//代码块1:第一次判空检查
if (instance == null) {
//代码块2:加锁,将方法锁改为锁代码块
synchronized (SingletonLazy3.class) {
//代码块3:进行第二次(双重)判空检查
if (instance == null) {
instance = new SingletonLazy4DCL();
}
}
}
return instance;
}
}
测试:
public class Main4DCL {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
}
}
六、进阶4:禁止指令重排
在对象的实例过程中,大概可分为以下3个步骤:
分配对象内存空间
在空间中创建对象
实例指向分配到的内存空间地址
由于实例化对象的过程不是原子性的,且JVM本身对Java代码指令有重排的操作,可能1-2-3的操作被重新排序成了1-3-2,这样就会导致在3执行完之后还没来得及创建对象时,其他线程先读取到了未初始化的对象instance并提前返回,在使用的时候会出现NPE空指针异常。
解决:给instance加volatile
关键字表明禁止指令重排,出现的概率不大, 但这是更安全的一种做法。
public class SingletonLazy5Volatile {
//加volatile关键字
private volatile static SingletonLazy5Volatile instance;
private SingletonLazy5Volatile() {
}
public static SingletonLazy5Volatile getInstance() {
//代码块1
if (instance == null) {
//代码块2:加锁,将方法锁改为锁代码块
synchronized (SingletonLazy3.class) {
//代码块3
if (instance == null) {
instance = new SingletonLazy5Volatile();
}
}
}
return instance;
}
}
七、进阶5:静态内部类
我们还可以使用静态类的静态变量被第一次访问时才会进行初始化的特性来进行懒加载初始化。把外部类的单例对象放到静态内部类的静态成员变量里进行初始化。
public class SingletonLazy6InnerStaticClass {
private SingletonLazy6InnerStaticClass() {
}
public static SingletonLazy6InnerStaticClass getInstance() {
return SingletonLazy6InnerStaticClass.InnerStaticClass.instance;
//或者写成return InnerStaticClass.instance;
}
private static class InnerStaticClass {
private static final SingletonLazy6InnerStaticClass instance = new SingletonLazy6InnerStaticClass();
}
}
虽然静态内部类里的写法和饿汉模式很像,但它却不是在外部类加载时就初始化了,而是在第一次被访问到时才会进行初始化的操作(即getInstance方法被调用时),也就起到了懒加载的效果,并且它可以保证线程安全。
测试:
public class Main6InnerStatic {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
}
}
反射攻击
虽然我们一开始都对构造器进行了私有化处理,但Java本身的反射机制却还是可以将private访问权限改为可访问,依旧可以创建出新的实例对象,这里以饿汉模式举例说明:
public class MainReflectAttack {
public static void main(String[] args) {
try {
SingletonHungry normal1 = SingletonHungry.getInstance();
SingletonHungry normal2 = SingletonHungry.getInstance();
//开始反射创建实例
Constructor<SingletonHungry> reflect = SingletonHungry.class.getDeclaredConstructor(null);
reflect.setAccessible(true);
SingletonHungry attack = reflect.newInstance();
System.out.println("正常静态方法调用获取到的对象:");
System.out.println(normal1);
System.out.println(normal2);
System.out.println("反射获取到的对象:");
System.out.println(attack);
} catch (Exception e) {
e.printStackTrace();
}
}
}
八、枚举单例(推荐使用)
public enum SingletonEnum {
INSTANCE;
}
枚举是最简洁、线程安全、不会被反射创建实例的单例实现,《Effective Java》中也表明了这种写法是最佳的单例实现模式。
单元素的枚举类型经常成为实现Singleton的最佳方法。 --《Effective Java》
为什么说不会被反射创建对象呢?查阅构造器反射实例化对象方法newInstance
的源码可知:反射禁止了枚举对象的实例化,也就防止了反射攻击,不用自己在构造器实现复杂的重复实例化逻辑了。
测试:
public class MainEnum {
public static void main(String[] args) {
SingletonEnum instance1 = SingletonEnum.INSTANCE;
SingletonEnum instance2 = SingletonEnum.INSTANCE;
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
}
总结:几种实现方式的优缺点 懒汉模式
优点:节省内存。
缺点:存在线程安全问题,若要保证线程安全,则写法复杂。
饿汉模式
优点:线程安全。
缺点:如果单例对象一直没被使用,则会浪费内存空间。
静态内部类
优点:懒加载并避免了多线程问题,写法相比于懒汉模式更简单。
缺点:需要多创建一个内部类。
枚举
优点:简洁、天生线程安全、不可反射创建实例。
缺点:暂无
来源:https://blog.csdn.net/weixin_38582659/article/details/112759822


猜你喜欢
- 前言 CLion是一款专为开发C及C++所设计
- 首先演示下效果,分段选择按钮,支持点击和滑动切换。视图绘制过程中,要执行onMeasure、onLayout、onDraw等方法,这也是自定
- Web Services 可以将应用程序转换为网络应用程序。通过使用 Web Services,您的应用程序可以向全世界发布信息,或提供某项
- 前言使用过SpringBoot的都应该知道,一个SpringBoot 项目就是由一个一个 Starter 组成的,一个 Starter 代表
- 本文实例讲述了Android持久化技术之SharedPreferences存储。分享给大家供大家参考,具体如下:1、SharedPrefer
- 现在,C#创建不规则窗体不是一件难事,下面总结一下:一、自定义窗体一般为规则的图形,如圆、椭圆等。做法:重写Form1_Paint事件(Fo
- 在数字科技日新月异的今天,软件和硬件的完美结合,造就了智能移动设备
- 示例 1 :使用搜索表单创建全屏模式我们要构建的小应用程序有一个应用程序栏,右侧有一个搜索按钮。按下此按钮时,将出现一个全屏模式对话框。它不
- jcasbin简介:jcasbin 是一个用 Java 语言打造的轻量级开源访问控制框架https://github.com/casbin/
- — 遇到问题今天在IDEA里面运行项目的时候报了一个错,如下图所示:— 找到问题根源其实控制台给出的错误信息提示说的很明显:类加载器加载文件
- 前 言终于来到下篇了,通过上篇,和中篇,我们了解了linq的基本语句,对应linq我们又了解到lambda表达式,静态扩展方法,以及linq
- 如何在WinForm中请求发送HTTP手工发送HTTP请求主要是调用 System.Net的HttpWebResponse方法手工发送HTT
- 废话不多说了额,直接给大家贴代码了,具体代码如下所示:/** * 下载指定路径的文件,并写入到指定的位置 * &
- 引言之前写了一篇关于 TraceId 的文章:为全局请求添加 TraceId ,看日志再也不懵逼今天就接着 TraceId 做一些优化,如果
- 本文实现Unity调用手机摄像,拍摄,然后识别二维码,显示二维码的内容。需要导入一个zxing.unity.dll文件,现在这个脚本的识别数
- 本篇博客要分享的一个UI效果——实现底部切换标签,想必大家在一些应用上面遇到过这种效果了,最典型的就是微信了,可以左右滑动切换页面,也可以点
- 程序中的错误分为编译时的错误和运行时的错误。编译时的错误主要是语法错误,比如:句尾没有加分号,括号不匹配,关键字错误等,这类错误比较容易修改
- 1 前言一般我们在Android的APP开发中,APP的界面如下: 可以看到,有状态栏、ActionBar(ToolBar)、导航
- 这篇文章主要介绍了Spring Cloud基于zuul实现网关过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学
- 1. 定义TreeMap的排序方法使用Comparator对象作为参数需要注意的是:排序方法是针对键的,而不是值的。如果想针对值,需要更麻烦