[concurrency-interest] Static initializer

Dhanji R. Prasanna dhanji at gmail.com
Tue Apr 10 09:40:50 EDT 2007


Im by no means a concurrency expert, but here's how I read it:

The static method cannot be invoked prior to the static initializer being
called (the static initializer is called as part of the classloading). The
final keyword ensures safe publication of the map to the instance. So
getInstance() is guaranteed to return fully initialized instances.

Classes load in a CL in a synchronized fashion so there is no danger of two
threads hitting the static initializer.

On 4/10/07, Mike Quilleash <mike.quilleash at subexazure.com> 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
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20070410/67555411/attachment-0001.html 


More information about the Concurrency-interest mailing list