Java 双重验证懒汉模式(synchronized和ReentrantLock)

一、synchronized 实现双重验证懒汉模式

注: volatile 防止出现指令重排序

/**
 * 测试单例
 */
public class TestSingleton {

    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);
    }

}

/**
 * 单利懒汉模式,采用双重校验
 */
class Singleton {

    private Singleton() {
    }

    private static volatile Singleton singleton = null;

    public static Singleton getInstance() {
        // 只有为null时候才创建
        if (singleton == null) {
            synchronized (Singleton.class) { // 保证执行的线程安全,不会产生多个对象
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

二、ReentrantLock 非公平锁实现双重验证懒汉模式

/**
 *  名称:单例懒汉模式
 *
 *  介绍:lock 重入锁,实现双重验证懒汉模式,并加以volatile修饰,防止出现低概率指令重排序
 */
public class LockStudy {

    Logger log = Logger.getLogger(this.getClass().getName());

    final static Lock lock = new ReentrantLock(false); // 定义非公平锁

    private LockStudy () {
    }

    private static volatile LockStudy lockStudy = null;

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

    public static void main(String[] args) {
        LockStudy lockStudy1 = LockStudy.getInstance();
        LockStudy lockStudy2 = LockStudy.getInstance();
        System.out.println(lockStudy1 == lockStudy2);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值