C1.overview
p1.concept
problems
- People can use reflect mechanism to create other instance to violate singleton.
- The safety of thread
- Instruction reordering
- Deserialization also can violate the integrity of singleton
solutions
- Static area solve reflect problems
- Double check locks
- Keyword of volatile
- 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;
}
}
标签:singleton,pattern,Singleton,private,instance,static,null
From: https://www.cnblogs.com/wshlblog/p/17221353.html