Re: JavaMemoryModel: Idiom for safe, unsynchronized reads

From: Bill Pugh (pugh@cs.umd.edu)
Date: Fri Jul 02 1999 - 16:27:10 EDT


At 11:04 AM -0700 7/2/99, Joshua Bloch wrote:
> > Do extra ordering guarantees apply only for writes inside constructors
> > or whether they extend to all writes that occur prior to publishing?
>
> I think constructors are a red herring (albeit a tempting one). I believe
>that any solution that works for this idiom:
>
> private static foo;
> public Foo {
> if (foo=null)
> foo = new Foo(...);
> return foo;
> }
>
>will also work for this one:
>
> private static foo;
> public Foo {
> if (foo=null) {
> private Foo baz = new Foo(...);
> baz.mumble(...);
> foo = baz;
> }
> return foo;
> }
>

I think these two are very different. We need to worry about both the
reorderings of the reads and the reorderings of the writes. On almost
all machines, a write barrier would be required to prevent the writes
from being reordered. Similarly, compiler optimizations could reorder
the writes. So to make either of these work, we need to come up with
rules about which writes can't be reordered, and then use memory
barriers to prevent the processor from reordering them, and rules to
keep the compiler from reordering them.

The set of writes reorderings that must be prohibited to guarantee
initialization safety is much smaller than the reorderings that must
be prohibited to allow the second example to work.

My thought is that second one would work only if synchronization is
used to indicate that the writes implied by baz.mumble(...) and the
write foo = bas can't be reordered. Perhaps

     private static foo;
     public Foo {
         if (foo=null) {
             private Foo baz = new Foo(...);
            synchronized(baz) {
                     baz.mumble(...);
                }
             foo = baz;
         }
         return foo;
     }

i.e., have a monitor unlock between the modification and the publish.

We can work out the details later of what synchronization idiom would
be required if we did support this. But the two are definitely not
the same, and the same techniques might not work for both (for
example, padding to the next cache line in the nursery works for
initialization safety, but doesn't work for
modify - publish - unsynchronized read).

        Bill

-------------------------------
This is the JavaMemoryModel mailing list, managed by Majordomo 1.94.4.

To send a message to the list, email JavaMemoryModel@cs.umd.edu
To send a request to the list, email majordomo@cs.umd.edu and put
your request in the body of the message (use the request "help" for help).
For more information, visit http://www.cs.umd.edu/~pugh/java/memoryModel



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