title: Java: Why doesn't deserialization invoke constructor & what's the best workaround?
body: <p>The <a href="http://java.sun.com/j2se/1.5/pdf/serial-1.5.0.pdf">Java serialization spec</a> for Java 1.5 said:</p>
  
  <blockquote>
    <p>For serializable objects, the no-arg constructor for the first
    non-serializable supertype is run. For serializable classes, the
    fields are initialized to the default value appropriate for its type.
    Then the fields of each class are restored by calling class-specific
    readObject methods, or if these are not defined, by calling the
    defaultReadObject method. Note that field initializers and
    constructors are not executed for serializable classes during
    deserialization.</p>
  </blockquote>
  
  <p>However, this means if we put a static variable (for example a counter variable) inside the class, it will not be updated as normally would:</p>
  
  <pre><code>class Foo {
      static int t;
  
      public Foo() {
          t++;
      }
  }
  
  public class Bar extends Foo implements Serializable {
      static int t;
  
      public Bar() {
          t++;
      }
  }
  </code></pre>
  
  <p>In this case, if one instance of <code>Bar</code> is deserialized, then the counter for <code>Foo</code> is correct and the counter for <code>Bar</code> is off-by-one.</p>
  
  <p>I wonder why does deserialization does not invoke the constructor? Since it seems that while this will gain a bit on speed, it can cause potential problems. The compiler could be easily designed to produce a "static constructor" that only updates the static variables that will be updated and does not rely on outside information when the class is loaded.</p>
  
  <p>Also, I wonder what is the best way to avoid this? The solution I can think of is packing the deserialization with the operation on the static variable.</p>
  
  <p>Thanks for any inputs in advance!</p>