singleton pattern

C1.overview

p1.concept

problems

  1. People can use reflect mechanism to create other instance to violate singleton.
  2. The safety of thread
  3. Instruction reordering
  4. Deserialization also can violate the integrity of singleton

solutions

  1. Static area solve reflect problems
  2. Double check locks
  3. Keyword of volatile
  4. Rewrite the method of readResolve

P2 .code

simple demo

public class Singleton implements Serializable {

    private static final long serialVersionUID = 1L;

    private static volatile Singleton instance;

    private Singleton() {
        // 防止通过反射机制创建新实例
        if (instance != null) {
            throw new RuntimeException("请使用getSingleton()方法获取单例实例");
        }
    }

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

    // 重写readResolve()方法,防止反序列化破坏单例
    private Object readResolve() throws ObjectStreamException {
        return instance;
    }
}
posted @ 2023-03-16 10:22  逆态度22  阅读(16)  评论(0)    收藏  举报