栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

写一个线程安全的单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

写一个线程安全的单例模式

写一个线程安全的单例模式

目录
    • 写一个线程安全的单例模式
      • 1、饿汉式
      • 2、懒汉式
      • 3、使用双重校验 + volatile
      • 4、枚举单例
      • 5、Lock
      • 6、AtomicReference + CAS

线程安全的单例模式有很多种写法:

1、饿汉式

我们以jdk源码为例,Runtime类的源码:
类加载为静态变量赋值。

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    private Runtime() {}
}

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、使用双重校验 + volatile

synchronized修饰代码块,volatile可见性。

public class Singleton {
	private static volatile Singleton instance = null;

	private Singleton() {}

	public static Singleton getInstance() {
	    if (instance == null) { // 先判断实例是否存在,不存在再加锁
	        synchronized (Singleton.class) {
	            if (instance == null) { // 多线程情况下,只有一个能进入,避免创建多个对象。
	                return instance = new Singleton();
	            }
	        }
	    }
	    return instance;
	}
	
}

4、枚举单例

一个枚举就是一个单例。

enum SingletonEnum {
    INSTANCE;
}

5、Lock
public class Singleton {
    private static Singleton instance;
    private static final Lock lock = new ReentrantLock();

    private Singleton() { }

    public static Singleton getInstance() {
        lock.lock();
        try {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        } finally {
            lock.unlock();
        }
    }
    
}

6、AtomicReference + CAS
public class Singleton {
    private static final AtomicReference instance = new AtomicReference();

    private Singleton() { }

    public static Singleton getInstance() {
        for (;;) {
            Singleton singleton = instance.get();
            if (null != singleton) {
                return singleton;
            }

            singleton = new Singleton();
            if (instance.compareAndSet(null, singleton)) {
                return singleton;
            }
        }
    }
    
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号