序列化对单例的破坏

首先来写一个单例的类:

code 1

package com.hollis;
import java.io.Serializable;
/**
 * Created by hollis on 16/2/5.
 * 使用双重校验锁方式实现单例
 */
public class Singleton implements Serializable{
    private volatile static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

接下来是一个测试类:

code 2

package com.hollis;
import java.io.*;
/**
 * Created by hollis on 16/2/5.
 */
public class SerializableDemo1 {
    //为了便于理解,忽略关闭流操作及删除文件操作。真正编码时千万不要忘记
    //Exception直接抛出
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //Write Obj to file
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
        oos.writeObject(Singleton.getSingleton());
        //Read Obj from file
        File file = new File("tempFile");
        ObjectInputStream ois =  new ObjectInputStream(new FileInputStream(file));
        Singleton newInstance = (Singleton) ois.readObject();
        //判断是否是同一个对象
        System.out.println(newInstance ==

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
  • 1970-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-19
  • 2021-07-12
  • 2021-09-13
  • 2021-12-20
  • 2022-01-09
相关资源
相似解决方案