[concurrency-interest] Static initializer

Mike Quilleash mike.quilleash at subexazure.com
Tue Apr 10 15:29:36 EDT 2007


Thanks for the replies guys.  Think I've got it straight in my head now.

Cheers.

Mike. 

-----Original Message-----
From: Brian Goetz [mailto:brian at quiotix.com] 
Sent: 10 April 2007 20:06
To: Mike Quilleash 
Cc: concurrency-interest at cs.oswego.edu
Subject: Re: [concurrency-interest] Static initializer

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


 This e-mail is bound by the terms and conditions described at http://www.subexazure.com/mail-disclaimer.html




More information about the Concurrency-interest mailing list