RE: JavaMemoryModel: Unsynchronized read as an optimization

From: Miles Sabin (MSabin@interx.com)
Date: Sat Dec 16 2000 - 10:23:51 EST


As an aid to my understanding of Roberts code fragment, where,

  GlobalSettings.ALLOW_UNSYNCHRONIZED_READ == true

is,

  class Foo {
    private Helper helper = null;
    private boolean helperExists;
    public Helper getHelper() {
      if (!helperExists)
        synchronized(this) {
          if (helper == null)
            helper = new Helper();
          else
            helperExists =
              GlobalSettings.ALLOW_UNSYNCHRONIZED_READ;
        }
      return helper;
    }
    // other functions and members...
  }

more or less equivalent to,

  class Foo
  {
    private final static int HELPER_DOESNT_EXIST = 0;
    private final static int HELPER_MIGHT_EXIST = 1;
    private final static int HELPER_EXISTS = 2;

    private int state = HELPER_DOESNT_EXIST;
    private Helper = null;

    public Helper getHelper()
    {
      switch(state)
      {
        case HELPER_DOESNT_EXIST:
        {
          synchronized(this)
          {
            if(helper == null)
              helper = new Helper();
            state = HELPER_MIGHT_EXIST;
          }

          // Drop through ...
        }

        case HELPER_MIGHT_EXIST:
        {
          synchronized(this)
          {
            state = HELPER_EXISTS;
          }

          // Drop through ...
        }

        case HELPER_EXISTS:
        {
          return helper;
        }
      }
    }
  }

ie., we have a pair of sync blocks in sequence acting as a
barrier?

Cheers,

Miles

-- 
Miles Sabin                               InterX
Internet Systems Architect                5/6 Glenthorne Mews
+44 (0)20 8817 4030                       London, W6 0LJ, England
msabin@interx.com                         http://www.interx.com/

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



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