双重检查锁单例模式
双重检查锁单例模式
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(); } }