[concurrency-interest] static initializers and threads

Bart Jacobs bart.jacobs at cs.kuleuven.be
Thu May 25 07:39:13 EDT 2006


The answer is in Section 12.4 of the Java Language Specification 
<http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4>. 


In fact, T2 waits for the initialization to finish before executing the 
constructor of A.

There's no need to synchronize the static block. As you can read in 
Section 12.4, the virtual machine performs the necessary synchronization 
automatically.

The only way to get a new object of A before the completion (normal or 
abrupt) of the static initializer is if the object is created from 
within the static initializer itself (directly or indirectly), i.e. by 
the thread that is executing the static initializer. But note that this 
includes nested class initializations; for example, if the static 
initializer of A triggers initialization of some class B, which in turn 
creates an object of A, then this object creation succeeds and you get 
an object of A prior to completion of the static initializer of A. 
However, note that such a circularity could also cause a deadlock, 
specifically if some other thread is already initializing B, so this 
would be buggy code to write in any case.

(Note that the static block should of course be inside the class body.)

Bart

teknokrat wrote:
> This a question on static initializers in Java. The answer may be in the 
> language spec but I have not been able to find it. I have the following 
> class;
>
> static {
> 	// do some initialization
> }
>
> class A {
>
> 	public A(){}
> }
>
> I have two threads T1, T2 executing
>
> A a = new A();
>
> Assuming T1 enters the static initializer first, what happens to T2? 
> Does it block waiting for the initialization to finish before being 
> given a reference to a?
>
> Should the static block be synchronized? Are there any conditions under 
> which its possible to get a new object a but with the initialization 
> incomplete?
>
> thanks
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>   

Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



More information about the Concurrency-interest mailing list