title: How to deal with Singleton along with Serialization
body: <p>Consider I have a Singleton class defined as follows.</p>
  
  <pre><code>public class MySingleton implements Serializable{
   private static MySingleton myInstance;
  
   private MySingleton(){
  
   }
    static{
      myInstance =new MySingleton();
   }
   public static MySingleton getInstance(){
      return MySingleton.myInstance;
   }
  }
  </code></pre>
  
  <p>The above definition according to me satisfies the requirements of a Singleton.The only additional behaviour added is that the class implements serializable interface.</p>
  
  <p>If another class X get the instance of the single and writes it to a file and at a later point deserializes it to obtain another instance we would have two instances which is against the Singleton principle.</p>
  
  <p>How can I avoid this or am I wrong in above definition itself.</p>