Thread safety of static blocks in Java

Viewed 12856

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 initializing SomeClass's Class object and is in the middle of initializing the values in the static block when a second thread wants to load SomeClass's Class again, 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?

5 Answers

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.

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

Static block is always thread safe while its getting initialzed. This is the reason use static variable of singleton object as one way of creating singleton object (singelton desing pattern).

Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time

refered from Java Language Specification

Related