Open wwq0912 opened 5 years ago
public class Singleton2 implements Serializable { private static final long serialVersionUID = -5809782578272943999L; private static Singleton2 instance = null; //懒汉 private Singleton2() { if (instance != null) { throw new RuntimeException("Against Reflection"); } } //Against multi-thread public synchronized static Singleton2 getSingleton2(String name) { if (null == instance) { instance = new Singleton2(); } return instance; } private Object readResolve() throws ObjectStreamException { // Against Serizlization if (null == instance) { instance = new Singleton2(); } return instance; } }
public class Lazy implements Runnable { private Thread t; private String threadName; Lazy(String name) { threadName = name; } public void run() { try { for (int i = 4; i > 0; i--) { Thread.sleep(50); Singleton2 test1 = Singleton2.getSingleton2(); SerializeMethod(test1); Singleton2 test2 = DeserializeMethod(); System.out.print("test Serizlization===="); System.out.println(test1 == test2); testReflection(test1); } } catch (Exception e) { System.out.println("Thread " + threadName + " interrupted."); } } public void start() { if (t == null) { t = new Thread(this, threadName); t.start(); } } public static void main(String args[]) { Lazy R1 = new Lazy("Thread-1"); R1.start(); Lazy R2 = new Lazy("Thread-2"); R2.start(); } private void testReflection(Singleton2 obj) { System.out.print("testReflection ====="); try { Constructor<Singleton2> constructor = Singleton2.class.getDeclaredConstructor(); constructor.setAccessible(true); Singleton2 obj2 = constructor.newInstance(); System.out.print("testReflection result====="); System.out.println( obj == obj2); }catch (Exception e) { System.out.println(e); } } public Singleton2 getObj() { Singleton2 test = Singleton2.getSingleton2(); return test; } private static void SerializeMethod(Singleton2 objTemp) throws FileNotFoundException, IOException { ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("C:/122/Singleton.txt"))); oo.writeObject(objTemp); oo.close(); } private static Singleton2 DeserializeMethod() throws Exception, IOException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("C:/122/Singleton.txt"))); Singleton2 singleton = (Singleton2) ois.readObject(); return singleton; } }
Singleton2.java
Lazy.java