Monday, 17 June 2019

Serialization | Serialization for Singleton Object

Serialization can cause breakage of singleton property of singleton classes. Serialization is used to convert an object of a byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.

//Java code to explain effect of Serilization on singleton classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Singleton implements Serializable {
      private static final long serialVersionUID = 1L;
      // public instance initialized when loading the class
      private static Singleton instance = new Singleton();
      private Singleton() {
            // private constructor
      }
      public static Singleton getInstance() {
            return instance;
      }
}
public class SingletonTest {
      public static void main(String[] args) {
            try (ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text"));
                        ObjectInput in = new ObjectInputStream(new FileInputStream("file.text"));) {
                 
                  Singleton instance1 = Singleton.getInstance();
                  out.writeObject(instance1);
                  // deserailize from file to object
                  Singleton instance2 = (Singleton) in.readObject();
                  System.out.println("instance1 hashCode: " + instance1.hashCode());
                  System.out.println("instance2 hashCode: " + instance2.hashCode());
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }
}
Output
instance1 hashCode: 1831932724
instance2 hashCode: 1747585824

As we can see in the above code, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.

Overcome serialization issue
To AVOID this scenario (multiple instance), implement readResolve() method and return the Singleton instance.

//Java code to explain the effect of Serialization on singleton classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Singleton implements Serializable {
      private static final long serialVersionUID = 1L;
      // public instance initialized when loading the class
      private static Singleton instance = new Singleton();
      private Singleton() {
            // private constructor
      }
      public static Singleton getInstance() {
            return instance;
      }
      // implement readResolve method
      protected Object readResolve() {
            return instance;
      }
}
public class SingletonTest {
      public static void main(String[] args) {
            try (ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text"));
                        ObjectInput in = new ObjectInputStream(new FileInputStream("file.text"));) {
                  Singleton instance1 = Singleton.getInstance();
                  out.writeObject(instance1);
                  // deserialize from file to an object
                  Singleton instance2 = (Singleton) in.readObject();
                  System.out.println("instance1 hashCode: " + instance1.hashCode());
                  System.out.println("instance2 hashCode: " + instance2.hashCode());
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }
}
Output
instance1 hashCode: 1831932724
instance2 hashCode: 1831932724

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...