线程安全的单例模式

单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。它有以下三个特点:

  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。

创建单例模式


  • 懒汉式(线程不安全)

所谓的懒汉式就是需要使用的时候才去创建实例。这种非线程安全的创建模式,懒加载很明显,不能够满足多线程条件下使用。
/**
 * 传统的懒汉式单例
 */
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}


  • 懒汉式(线程安全)

通过synchronized关键字可以实现线程安全的懒汉式单例,但是似乎还有更好的方法。
/**
 * 线程安全的懒汉式单例
 */
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (null == instance) {
            instance = new Singleton();
        }
        return instance;
    }
}


  • 饿汉式(线程安全)

饿汉式即在类装载的时候就进行了实例化。但是很这样会导致无法懒加载,效率很低,浪费系统资源。
/**
 * 线程安全的饿汉式单例
 */
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}


  • 静态内部类

静态内部类相比饿汉式创建单例有一处优点,就是创建实例的时候并不是在类装载的时候。而是主动通过SingletonHolder类,调用getInstance方法的时候,才会去实例化。这样就很合理的节省资源。
/**
 * 线程安全的静态内部类单例
 */
public class Singleton {
    private Singleton() {}
    private static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}


  • 双重校验锁

通过两次的判断,让创建两个不同的实例对象成为不可能。
/**
 * 线程安全的双重校验锁单例
 */
public class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        // 先检查实例是否存在,如果不存在才进入下面的同步块  
        if (null == instance) {
            // 同步块,线程安全地创建实例  
            synchronized (Singleton.class) {
                // 再次检查实例是否存在,如果不存在才真正地创建实例  
                if (null == instance) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33764491/article/details/79820654