Re: JavaMemoryModel: Double-Checked Locking is Broken

From: Paul Haahr (paul@paulhaahr.com)
Date: Sun Feb 10 2002 - 19:00:00 EST


> Just wonder if the following code will work in the specific case of a
> static singleton object of a class:
>
> public class Singleton {
> private static Singleton instance;
> // other non-static member fields ...
> private Singleton() {
> // do whatever necessary for the non-static member fields...
> }
> public static Singleton getInstance() {
> if (instance == null) {
> synchronized(Singleton.class) {
> if (instance == null) {
> instance = new Singleton();
> }
> }
> }
> return instance;
> }
> }
>
> Specifically, when the caller gets the object back from
> Singleton.getInstance(), is the Singleton object guaranteed to be fully
> initialized for the non-static member fields via the constructor in the
> current Java Memory Model in a platform independent way ? (i.e Does it work
> in the presence of either optimizing compilers or shared memory
> multiprocessors ?)

Nope. The usual problem with double-checked locking still applies:
threads can read the instance without being properly synchronized with
the thread that writes the instance variable.

The following should work, though:

  public class Singleton {
    private final static Singleton INSTANCE = new Instance();
    private Singleton() { ... }
    public static Singleton getSingleton() {
      return INSTANCE;
    }
  }

because final static variables are initialized in a manner that is
visible to any thread which uses the class. (Similar to final instance
variables and instances of a class.)

--p
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:38 EDT