[concurrency-interest] Static initializer

Brian Goetz brian at quiotix.com
Tue Apr 10 15:05:59 EDT 2007


Short answer: yes, this code is safe.

In this particular case, the work is done by the final field semantics 
and the effective immutability of the MyClass.  All the initialization 
is done in the ctor, all the state is reachable through the final field 
'map', and no modifications to the state are ever made subsequently. 
Initialization safety guarantees that any thread obtaining a reference 
to a MyClass sees the correct state.

The static initialization is a sensible way to publish this, regardless 
of thread-safety.  But if there was any state not reachable through 
final fields, you would need the static initializer (or some other safe 
publication mechanism) to ensure visibility.

Mike Quilleash wrote:
> Hi all,
>  
> Just a quick question about static initializers.  I've read JCiP 
> (excellent book BTW) and wondered if the following is threadsafe.  The 
> examples in the book didn't quite cover this case (code/method calls in 
> the constructor).
>  
>  
> public class MyClass
> {
>    private static MyClass instance = new MyClass();
>  
>    private final Map map;
>  
>    private MyClass()
>    {
>       // do some init work
>  
>       map = Collections.unmodifiableMap( ... );
>    }
>  
>    public static MyClass getInstance()
>    {
>        return instance;
>    }
>  
>    // other accessor method(s) to access info in the map
> }
>  
>  
> Is any thread that calls getInstance() guaranteed to see a fully 
> initialized MyClass instance?  If so, is this because of the static 
> initialization, or the "final" someObject, or both?  I'd like to know 
> before I go and use this pattern everywhere in my code!
>  
> Thanks.
>  
> Mike.
>  
> 
>  This e-mail is bound by the terms and conditions described at http://www.subexazure.com/mail-disclaimer.html
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest


More information about the Concurrency-interest mailing list