public static void breakSingletonWithSerialization() { System.out.println(); final String fileName = "singleton.ser"; // getting singleton instance Singleton instanceOne = Singleton.getInstance(); instanceOne.setValue(10); try { // Serialize to a file ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream(fileName)); objectOutput.writeObject(instanceOne); objectOutput.close(); // now changed the value of singleton instanceOne.setValue(20); // Serialize to a file ObjectInput objectInput = new ObjectInputStream(new FileInputStream(fileName)); Singleton instanceTwo = (Singleton) objectInput.readObject(); objectInput.close(); System.out.println("Instance One Value= " + instanceOne.getValue()); System.out.println("Instance Two Value= " + instanceTwo.getValue()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public static void main(String[] args) { Singleton s = Singleton.getReference(); System.out.println(s.getValue()); Singleton s2 = Singleton.getReference(); s2.setValue(9); System.out.println(s.getValue()); try { // Can't do this: compile-time error. // Singleton s3 = (Singleton)s2.clone(); } catch (Exception e) { e.printStackTrace(System.err); } }