Re: JavaMemoryModel: Will this solution work?

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Wed Sep 17 2003 - 07:46:18 EDT


> Srinivas Kunani wrote:
> > Will the following code resolve the problem. If it will
> > not, can somebody please explain why not.
> > ...
> > private static Singleton instance;
> > private static Object mutex = new Object();
> > private static boolean initialized = false;
> >
> > private Singleton() {
> > }
> >
> > public static Singleton getInstance() {
> > if (instance == null || ! initialized) {
> > synchronized(mutex) {
> > if (instance == null ) {
> > instance = new Singleton();
> > initialized = (instance.getClass() != null);
> > }
> > }
> > }
> > return instance;
> > }
>
> I think what Srinivas is relying on here is the implicit
> synchronization that occurs with class loading and initialization.
> There is an assumption that instance.getClass() will lock the Class
> object, and similarly that any reader thread that invokes
> getInstance() will first lock the Class object to determine if this
> class has been initialized yet. Hence there would be a common lock
> involved and this *could* be correctly synchronized.

I am going to display my ignorance here: is acquiring a lock when invoking
getClass() mentioned anywhere in the spec?

Also, it wouldn't help even if a lock were acquired when invoking
getClass() and before the invocation of getInstance(). There is no
guarantee that the acquire of the lock by the reader thread will happen
after the release of the lock by the writer thread. The reader could grab
its lock first. Then there would no unlock / lock pair between the
initialization of the fields and reads of them by the reader thread.

As I mentioned, in such a case, there is no guarantee that subsequent
reads by the reader will see the correctly initialized values. This
behavior can be seen in practice on the Alpha, IIRC.

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



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