双重检查锁单例模式

双重检查锁单例模式

import java.io.Serializable;

/**
 * 双重检查锁单例模式
 * 描述:
 *
 * @author lyn
 * @date 2022/3/2 17:16
 */
public class SingleBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private static volatile SingleBean instance;

    private SingleBean() {
        //防止反射破坏代理模式
        if (instance != null) {
            throw new RuntimeException();
        }
    }

    public static SingleBean getInstance() {
        if (instance == null) {
            synchronized (SingleBean.class) {
                if (instance == null) {
                    instance = new SingleBean();
                }
            }
        }
        return instance;
    }

    /**
     * 防止序列化破坏单例模式
     *
     * @return
     */
    private Object readResolve() {
        return getInstance();
    }
}

 

 

posted @ 2022-03-02 18:35  进击的小蔡鸟  阅读(73)  评论(0编辑  收藏  举报