RE: JavaMemoryModel: Will this solution work?

From: Boehm, Hans (hans_boehm@hp.com)
Date: Wed Sep 17 2003 - 16:47:44 EDT


Also section 12.4.3 explicitly gives the implementation the option of removing the
initialization test from the code once the class is initialized. Relying on the
implicit synchronization in the initialization code seems extremely dangerous.

Hans

> -----Original Message-----
> From: Jeremy Manson [mailto:jmanson@cs.umd.edu]
> Sent: Wednesday, September 17, 2003 4:46 AM
> To: David Holmes
> Cc: Srinivas_Kunani@toyota.com; javaMemoryModel@cs.umd.edu
> Subject: Re: JavaMemoryModel: Will this solution work?
>
>
> > 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
-------------------------------
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