title: Class initialization and synchronized class method
body: <p>In my application, there is a class like below:</p>
  
  <pre><code>public class Client {
      public synchronized static print() {
          System.out.println("hello");
      }
  
      static {
          doSomething(); // which will take some time to complete
      }
  }
  </code></pre>
  
  <p>This class will be used in a multi thread environment, many threads may call the Client.print() method simultaneously. I wonder if there is any chance that thread-1 triggers the class initialization, and before the class initialization complete, thread-2 enters into print method and print out the "hello" string?</p>
  
  <p>I see this behavior in a production system (64 bit JVM + Windows 2008R2), however, I cannot reproduce this behavior with a simple program in any environments.</p>
  
  <p>In Java language spec, section 12.4.1 (http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html), it says:</p>
  
  <blockquote>
    <p>A class or interface type T will be initialized immediately before the first occurrence of any one of the following:</p>
    
    <ul>
    <li>T is a class and an instance of T is created.</li>
    <li>T is a class and a static method declared by T is invoked.</li>
    <li>A static field declared by T is assigned.</li>
    <li>A static field declared by T is used and the reference to the field is not a compile-time constant (§15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization. </li>
    </ul>
  </blockquote>
  
  <p>According to this paragraph, the class initialization will take place before the invocation of the static method, however, it is not clear if the class initialization need to be <em>completed</em> before the invocation of the static method. JVM should mandate the completion of class initialization before entering its static method according to my intuition, and some of my experiment supports my guess. However, I did see the opposite behavior in another environment. Can someone shed me some light on this?</p>
  
  <p>Any help is appreciated, thanks.</p>