3
public static class Singleton implements Serializable {
    private static Singleton ourInstance;

    public static Singleton getInstance() 
    {
        if (ourInstance == null) 
        {
            ourInstance = new Singleton();
        }
        return ourInstance;
    }     
    private Singleton() {
    }
}

     Singleton instance = Singleton.getInstance();
     objectOutputStr.writeObject(instance);
      Singleton singleton1 = (Singleton) objInputStr.readObject();
      Singleton singleton2 = (Singleton) objInputStr.readObject();
      System.out.println(singleton1);//A
      System.out.println(singleton2);//B

Why different outputs for singleton1 and singleton2(lines marked A and B). Is it possible to make the two references to be same.

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
kurumkan
  • 2,635
  • 3
  • 31
  • 55
  • 1
    You are writing one instance to the stream, then you read it twice. That's not going to work like you posted it. – f1sh Mar 02 '16 at 16:31
  • Ops, someone closed the question while editing my response: – idelvall Mar 02 '16 at 17:17
  • Singleton means that this object is the only instance of the class. This only has sense **at runtime**, and it is completely circumstantial (depends on your app logic, not in any language restriction). So the serialization process can not store this feature of the object. On the other hand, the serialization protocol do not store any other information about the instance number or id, in other words, different instances with the same structure are indistinguishable after serialization. So no, it´s not possible, except you handle this in your application logic, of course. – idelvall Mar 02 '16 at 17:18

1 Answers1

0

Try re-running your application with the line I added as follows:

  Singleton instance = Singleton.getInstance();
  objectOutputStr.writeObject(instance);
  Singleton singleton1 = (Singleton) objInputStr.readObject();
  objectOutputStr.writeObject(instance); //Added an additional write to stream
  Singleton singleton2 = (Singleton) objInputStr.readObject();
  System.out.println(singleton1);//A
  System.out.println(singleton2);//B
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
  • thanks, but that is my mistake - objectoutputstreams can be different. but the result will be the same – kurumkan Mar 02 '16 at 17:26