guguoyi / shareber

7 stars 0 forks source link

2018-12-07[Paul Hu] Singleton #4

Open hwlwsy123 opened 5 years ago

hwlwsy123 commented 5 years ago

package com.gravity.rest.user;

import java.io.ObjectStreamException; import java.io.Serializable;

public class MySingleton implements Serializable {

private static final long serialVersionUID = 1L;
private static MySingleton instance = new MySingleton();

private MySingleton() {
}

public static MySingleton getInstance() {
    return instance;
}

protected Object readResolve() throws ObjectStreamException {
    System.out.println("Call readResolve method!");
    return instance;
}

}

------------------Test------------------- package com.gravity.rest.user;

import java.io.*;

public class SerializableTest extends Thread {

@Override
public void run() {
    MySingleton singleton = MySingleton.getInstance();

    File file = new File("D://MySingleton.txt");
    try {
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(singleton);
        fos.close();
        oos.close();
        System.out.println(singleton.hashCode());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        MySingleton rSingleton = (MySingleton) ois.readObject();
        fis.close();
        ois.close();
        System.out.println(rSingleton.hashCode());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    for(int i = 0; i< 10; i++) {
        Thread thread = new SerializableTest();
        thread.start();
    }
}

}

--------Output-------------- 2049029316 2049029316 2049029316 2049029316 2049029316 2049029316 2049029316 2049029316 2049029316 2049029316 Call readResolvemethod! 2049029316 Call readResolvemethod! 2049029316 Call readResolvemethod! Call readResolvemethod! 2049029316 Call readResolvemethod! Call readResolvemethod! 2049029316 2049029316 Call readResolvemethod! Call readResolvemethod! 2049029316 2049029316 2049029316 Call readResolvemethod! Call readResolvemethod! 2049029316 2049029316