本帖最后由 肥猫 于 2013-8-7 17:47 编辑
你这个就是反序列化机制对单例模式的破坏了,对于这个只要在你的单例源码总加上readResolve()这个方法就能防止反序列化的破坏.- public class Singleton implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String name;
- private static Singleton s;
- private Singleton(String name){
- this.name = name;
- }
- private Object readResolve()throws ObjectStreamException{
- return s;
- }
- @Test
- public static Singleton getInstance(String name){
- if(s == null){
- synchronized(Singleton.class){
- if(s ==null){
- s = new Singleton(name);
- }
- }
- }
- return s;
- }
- }
复制代码- public class SingletonTest implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public static void main(String[] args)throws Exception {
- Singleton s = Singleton.getInstance("一条大菜狗");
- Singleton s2 = null;
- ObjectOutputStream oos = null;
- ObjectInputStream ois = null;
- Thread t1 = new Thread(new ThreadTest());
- Thread t2 = new Thread(new ThreadTest());
- t1.start();
- t2.start();
- try{
- oos = new ObjectOutputStream(new FileOutputStream("b.bin"));
- ois = new ObjectInputStream(new FileInputStream("b.bin"));
- oos.writeObject(s);//序列化S
- oos.flush();
- s2 = (Singleton)ois.readObject();//反 序列化S2
- System.out.println(s==s2);
- }finally{
- if(oos!=null){
- oos.close();
- }
- if(ois!=null){
- ois.close();
- }
- }
- }
- }
复制代码 |