RE: JavaMemoryModel: Will this solution work?

From: David Holmes (dholmes@dltech.com.au)
Date: Wed Sep 17 2003 - 02:51:30 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.

However, I don't believe that VM's actually acquire the lock on the
Class object on every static access. Given a "global" memory barrier
after the actual class initialization, and some form of
synchronization to see that the class has been initialized, the actual
locking of the Class object can be elided. Hence a reader thread would
no longer be synchronising with the writer thread.

Of course if that was what was being relied upon then a simpler
solution would have been to do:

 public static Singleton getInstance() {
  if (instance == null) {
     synchronized(Singleton.class) {
          if (instance == null ) {
              instance = new Singleton();
          }
     }
  }
  return instance;
 }

and, of course, if you were implicitly locking the Class object due to
the static invocation, then you missed the whole point of the
double-check idiom, which is to elide the lock on the reader path. ;-)

Of course, I may have completely misunderstood what Srinivas was
suggesting.

David Holmes

-------------------------------
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