小小的单例模式看着简单,其实里面道道着实不少。不仅要在多线程下保证实例唯一,也要能抵御序列化以及反射对单例的破坏。
要同时解决这么多问题,说难也难,说简单也简单。在《Effective Java》这本书中最推荐的单例写法就是使用枚举来实现单例。枚举类天然的能同时满足多线程安全问题以及抵御序列化和反射对单例的破坏的问题。
枚举单例实现
/**
* @Author: ming.wang
* @Date: 2019/2/22 14:05
* @Description: 枚举实现单例
*/
public enum EnumInstance {
INSTANCE,;
private Date birthDay;
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
public static EnumInstance getInstance()
{
return INSTANCE;
}
}
分析
下面我们分析一下,为什么枚举类能起到如此“逆天”的功能。
- 枚举vs多线程安全
首先我们分析一下,为什么枚举类可以保证线程安全。此处我们需要用到一个很牛叉的反编译工具jad,可支持linux、windows和苹果系统。下载完之后,我们使用jad来反编译一下EnumInstance.class(命令为jad \..\EnumInstance.class
),然后生成了EnumInstance.jad文件,我们打开它
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: EnumInstance.java
package com.wangming.pattern.creational.singleton;
import java.util.Date;
public final class EnumInstance extends Enum
{
public static EnumInstance[] values()
{
return (EnumInstance[])$VALUES.clone();
}
public static EnumInstance valueOf(String name)
{
return (EnumInstance)Enum.valueOf(com/wangming/pattern/creational/singleton/EnumInstance, name);
}
private EnumInstance(String s, int i)
{
super(s, i);
}
public Date getBirthDay()
{
return birthDay;
}
public void setBirthDay(Date birthDay)
{
this.birthDay = birthDay;
}
public static EnumInstance getInstance()
{
return INSTANCE;
}
public static final EnumInstance INSTANCE;
private Date birthDay;
private static final EnumInstance $VALUES[];
static
{
INSTANCE = new EnumInstance("INSTANCE", 0);
$VALUES = (new EnumInstance[] {
INSTANCE
});
}
}
通过反编译之后,一切秘密尽在眼前,原来它内部是执行了静态代码块,和饿汉式代码有异曲同工之妙,前面我们分析了当一个Java类第一次被真正使用到的时候静态资源被初始化、Java类的加载和初始化过程都是线程安全的。所以,创建一个enum类型是线程安全的。
- 枚举vs序列化和反序列化
我们贴上完整的代码测试
package com.wangming.pattern.creational.singleton;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
/**
* @Author: ming.wang
* @Date: 2019/2/21 16:05
* @Description: 使用反射或反序列化来破坏单例
*/
public class DestroySingletonTest {
public static void main(String[] args) throws Exception {
//序列化方式破坏单例 测试
serializeDestroyMethod();
//反射方式破坏单例模式 测试
// reflectMethod();
}
private static void reflectMethod() throws Exception {
// reflectHungryMethod();
// reflectLazyMethod();
reflectLazyMethod2();
}
private static void reflectHungryMethod() throws Exception {
//同理StaticInnerClassSingleton
HungrySingleton hungrySingleton = null;
HungrySingleton hungrySingleton_new = null;
Class singletonClass = HungrySingleton.class;
Constructor declaredConstructor = singletonClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
hungrySingleton = HungrySingleton.getInstance();
hungrySingleton_new = (HungrySingleton) declaredConstructor.newInstance();
System.out.println(hungrySingleton == hungrySingleton_new);
}
/**
* 验证使用对象空判断是否可抵御反射攻击
* @throws Exception
*/
private static void reflectLazyMethod() throws Exception {
LazySingleton lazySingleton = null;
LazySingleton lazySingleton_new = null;
Class singletonClass = LazySingleton.class;
Constructor declaredConstructor = singletonClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
lazySingleton = LazySingleton.getInstance();
lazySingleton_new = (LazySingleton) declaredConstructor.newInstance();
System.out.println(lazySingleton == lazySingleton_new);
}
/**
* 验证使用标志位是否可抵御反射攻击
* @throws Exception
*/
private static void reflectLazyMethod2() throws Exception {
LazySingleton lazySingleton = null;
LazySingleton lazySingleton_new = null;
Class singletonClass = LazySingleton.class;
Constructor declaredConstructor = singletonClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
lazySingleton_new = (LazySingleton) declaredConstructor.newInstance();
Field flag = singletonClass.getDeclaredField("flag");
flag.setAccessible(true);
flag.set(lazySingleton_new,true);
lazySingleton = LazySingleton.getInstance();
System.out.println(lazySingleton == lazySingleton_new);
}
private static void serializeDestroyMethod() throws IOException, ClassNotFoundException {
// HungrySingleton intance=null;
// HungrySingleton intance_new=null;
// StaticInnerClassSingleton intance = null;
// StaticInnerClassSingleton intance_new = null;
EnumInstance intance = null;
EnumInstance intance_new = null;
// hungrySingleton=HungrySingleton.getInstance();
// intance = StaticInnerClassSingleton.getInstance();
intance=EnumInstance.getInstance();
intance.setBirthDay(new Date());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(intance);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
// hungrySingleton_new= (HungrySingleton) ois.readObject();
// intance_new = (StaticInnerClassSingleton) ois.readObject();
intance_new = (EnumInstance) ois.readObject();
System.out.println(intance == intance_new);
System.out.println(intance.getBirthDay() == intance_new.getBirthDay());
}
}
运行结果是两个true。原因我们也简单提示一下,在讨论单例模式的攻击之序列化与反序列化这篇文章中,我们分析了ObjectInputStream.readObject()方法,其中一处代码
....
case TC_ENUM:
return checkResolve(readEnum(unshared));
case TC_OBJECT:
return checkResolve(readOrdinaryObject(unshared));
....
很显然我们此时是要走case TC_ENUM: return checkResolve(readEnum(unshared));
这个分支。然后看readEnum(unshared)
方法,你就知道为啥了。
- 枚举vs反射
为啥枚举能抵御几乎万能的反射呢?原因就在Constructor.newInstance()方法(Class.newInstance()最终调用的也是这个方法)。我们跟进去看下源码
....
@CallerSensitive
public T newInstance(Object ... initargs)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, null, modifiers);
}
}
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
ConstructorAccessor ca = constructorAccessor; // read volatile
if (ca == null) {
ca = acquireConstructorAccessor();
}
@SuppressWarnings("unchecked")
T inst = (T) ca.newInstance(initargs);
return inst;
}
.....
看到了吗if ((clazz.getModifiers() & Modifier.ENUM) != 0) throw new IllegalArgumentException("Cannot reflectively create enum objects");
当判断是枚举类的时候,就直接抛出异常了。
结论
上面的疑惑基本解开,我们在运用单例模式的时候,最推荐的做法就是使用枚举类来实现单例!
网友评论