How to prevent Serialization to break a Singleton Class Pattern?


A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using serialization, we can still create multiple instance of a class. See the example below −

Example - Breaking Singleton

 Live Demo

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Tester{
   public static void main(String[] args)
   throws ClassNotFoundException, IOException{

      A a = A.getInstance();
      A b = (A) getSerializedCopy(a);

      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }

   public static Object getSerializedCopy(Object sourceObject)
   throws IOException, ClassNotFoundException {
      ObjectOutputStream objectOutputStream = null;
      ObjectInputStream objectInputStream = null;
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      objectOutputStream.writeObject(sourceObject);
      objectOutputStream.flush();
      objectInputStream = new ObjectInputStream(

      new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
      return objectInputStream.readObject();
   }
}

class A implements Serializable {
   private static A a;
   private A(){}

   public static A getInstance(){
      if(a == null){
         a = new A();
      }
      return a;
   }
}

Output

1550089733
865113938

Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −

Override readResolve() method in the singleton class.

Example - Protecting Singleton

// implement readResolve method
protected Object readResolve() {
   return a;
}

Output

1550089733
1550089733

Updated on: 23-Jun-2020

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements