views:

1452

answers:

3

Let's say I have some Java code:

public class SomeClass {
    static {
        private final double PI = 3.14;
        private final double SOME_CONSTANT = 5.76;
        private final double SOME_OTHER_CONSTANT = 756.33;
    }

  //rest of class
}

If a thread is instantiating an instance of SomeClass and is in the middle of initializing the values in the static block when a second thread instantiates a second instance of SomeClass, what happens to the static block? Does the second thread ignore it assuming it's already initialized even though the first thread is not done? Or does something else happen?

+7  A: 

Static class initialization is guaranteed to be thread-safe by Java.

Dave Ray
+8  A: 

If the first thread hasn't finished initializing SomeClass, the second thread will block.

This is detailed in the Java Language Specification in section 12.4.2.

Jon Skeet
+1  A: 

watch out that you dont call code that require the lock for the class being initialized - it will deadlock. see this blog post: http://ramblingabout.wordpress.com/2008/04/10/deadlock-quiz-the-answer/

Chii