Re: JavaMemoryModel: A new box for the Java Memory model

From: Doug Lea (dl@altair.cs.oswego.edu)
Date: Wed Nov 10 1999 - 07:08:11 EST


> >In any case extending the semantics to cover array elements would be for
> >completeness only. The new semantics of volatile and final can be defined
> >without any reference to arrays.
>
> I don't get it. Do we need it or don't we?

For final arrays, yes, although Bill still thinks he can work around it.

For volatile arrays, the answer is more complicated since in many
(most? all?) cases you wouldn't want it. If you have an array that can
be asynchronously updated by multiple threads, right now you have two
choices:
  * synchronize the methods (or at least the relevant parts of
    methods). This is a cheap way of protecting a lot of
    updates to array elements at once, which normally would require
    exclusion anyway.

  * Use indirection. Create an array of references to:
    
     class VolatileRef {
       public volatile Object ref = null;
    }

   and intialize all of them. (The same thing works if the elements
   are all volatile ints, floats, etc too.) Ideally, you'd normally like
   to declare these arrays as final.

The second version uses more memory, but can win big in minimizing
cache thrashing (false sharing) when the array elements are constantly
being updated, since it spreads out the modified elements across more
cache lines. I use this to hold the array for the main double-ended
queue in my fork/join framework, and it actually provides better
performance (on multiway sparcs anyway) than any other solution I've
tried.

BTW, I briefly mention and illustrate this and a few other issues
involving volatiles in Section 4.4 of 2nd edition of CPJ book.

Another quick digression: I'm a little concerned about too-glibly
propagating the "add a volatile qualifier" patchup advice. More often
than not, if people have unexpected visibility problems due to
multiple threads, they also have unexpected atomicity/exclusion
problems that require synchronization, not volatiles. For example,
as a rule of thumb, it is never a good idea to declare a counter
as volatile.

-Doug

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



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