通过DCL创建单例类
package org.example;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Singleton {
private static volatile Singleton singleton;
private Singleton(){}
public static Singleton getInstance(){
if (singleton == null){
synchronized (Singleton.class){
if (singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
但是以上单例并不能真正保证单例,通过反射的方式就可以打破单例。
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Singleton instance = Singleton.getInstance();
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
Singleton newInstance = constructor.newInstance();
System.out.println(instance == newInstance);
}
以上输出的结果为false,表名存在了两个实例。
如何修复呢?
让反射无法成功即可。
修改构造函数
private Singleton(){
if (singleton != null){
throw new RuntimeException("单例只能创建一次");
}
}
通过以上方式,是否实现了单例呢?修改以上单例实现java.io.Serializable接口,保证可以对这个单例进行序列化操作。然后执行以下代码
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, ClassNotFoundException {
Singleton instance = Singleton.getInstance();
// 序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("TEMP"));
oos.writeObject(instance);
// 反序列化
File file = new File("TEMP");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Singleton newInstance2 = (Singleton)ois.readObject();
System.out.println(newInstance2 == instance);
}
结果返回false。
说明单例再次被打破。通过序列化和反序列化的方式打破了单例模式。
该如何处理呢?
public class Singleton implements Serializable{
private static volatile Singleton singleton;
private Singleton(){
if (singleton != null){
throw new RuntimeException("单例只能创建一次");
}
}
public static Singleton getInstance(){
if (singleton == null){
synchronized (Singleton.class){
if (singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
private Object readResolve(){
return singleton;
}
}
在类中添加一个readResolve方式指定要返回的对象的生成策略,就可以防止单例模式被破坏了。
具体参考java.io.ObjectInputStream#readOrdinaryObject源码
if (obj != null &&
handles.lookupException(passHandle) == null &&
desc.hasReadResolveMethod())
{
Object rep = desc.invokeReadResolve(obj);
if (unshared && rep.getClass().isArray()) {
rep = cloneArray(rep);
}
if (rep != obj) {
// Filter the replacement object
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, obj = rep);
}
}