Re: JavaMemoryModel: Word tearing

From: Doug Lea (dl@altair.cs.oswego.edu)
Date: Thu Jan 03 2002 - 10:37:19 EST


One of the harder cases to deal with about word-tearing is when
different threads all write into different, adjacent elements of a
shared array. As in:

class SharedArray {
   final static int N = 100;
   final static byte[] array = new byte[N];

   public static void main(String[] args) {
     for (int i = 0; i < N; ++i) {
        final int index = i;
        Thread t = new Thread() {
            volatile int old = 0;
            public void run() {
              for (int k = 0; k < 10000000; ++k) {
                int current = ++array[index];
                if ((current & 0xFF) != ((old+1) & 0xFF)) throw new Error();
                old = current;
              }
            }
          };
        t.start();
     }
  }
}

Can/should we say that this is guaranteed to work only if "array" is
declared as "volatile"? The argument here is that the array itself is
shared, so should be marked as volatile (even though none of its
elements are shared). This is basically the same story we give for
other uses of volatile arrays. (The underlying snag is, as usual,
that there is not syntax to declare the elements of arrays final or
volatile.)

This might be enough of a hook so that compilers could do the right
thing (here, maybe use 32bits for the elements) on machines otherwise
susceptible to word-tearing.

(BTW, this code runs without error on multiway sparcs using hotspot 1.4beta3)

-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:37 EDT