懒汉式单例类

/**
 * 懒汉式单例类
 * 懒汉式是典型的时间换空间
 * @author MJ
 *
 */
public class LazySingleton {
    private static LazySingleton instance = null;

    // 私有构造方法
    private LazySingleton() {
    }

    // 静态工厂方法
    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

 

饿汉式单例类

/**
 * 饿汉式单例类
 * 饿汉式是典型的空间换时间
 * @author MJ
 *
 */
public class EagerSingleton {
    private static EagerSingleton instance = new EagerSingleton();
    
    /**
     * 私有构造方法
     */
    private EagerSingleton(){}
    
    //静态工厂方法
    public static EagerSingleton getInstance() {
        return instance;
    }
}

 

双重检查加锁

/**
 * 双重检查加锁
 * 提示:由于volatile关键字可能会屏蔽掉虚拟机中一些必要的代码优化,所以运行效率并不是很高。因此一般建议,没有特别的需要,不要使用。
 * 也就是说,虽然可以使用“双重检查加锁”机制来实现线程安全的单例,但并不建议大量采用,可以根据情况来选用。
 * 
 * @author MJ
 *
 */
public class Singleton {
    private volatile static Singleton instance = null;

    private Singleton() {
    }

    // 静态工厂方法
    public static Singleton getInstance() {
        // 先检查实例是否存在,如果不存在才进入下面的同步快
        if (instance == null) {
            // 同步块,线程安全的创建实例
            synchronized (Singleton.class) {
                // 再次检查实例是否存在,如果不存在才真正的创建实例
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

相关文章:

  • 2022-03-06
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2021-06-27
  • 2021-05-08
猜你喜欢
  • 2021-12-05
  • 2021-06-26
相关资源
相似解决方案