Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of static blocks in Java

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?

like image 888
Ryan Thames Avatar asked Jan 20 '09 19:01

Ryan Thames


People also ask

How do I make a static thread-safe?

Now if you want to make this method really thread safe then one simple thing you can do. Either use non-mutable variables / objects or do not change / modify any method parameters.

Is static initialization thread-safe Java?

Yes, Java static initializers are thread safe (use your first option). However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.

Is static instance thread-safe?

Static constructors are always thread safe. The runtime guarantees that a static constructor is only called once. So even if a type is called by multiple threads at the same time, the static constructor is always executed one time.


1 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.

like image 68
Jon Skeet Avatar answered Oct 06 '22 08:10

Jon Skeet