Re: JavaMemoryModel: final fields, again

From: Bill Pugh (pugh@cs.umd.edu)
Date: Wed Jul 30 2003 - 15:53:29 EDT


At 8:23 PM -0400 7/29/03, Jeremy Manson wrote:
>Hi,
>
>> Assume T has a field x, and o and p are of class C with final field f.
>>
>> Initially q is null.
>>
>> Assume thread 1 does
>>
>> o.f = new T();
>> freeze o.f;
>> q = o;
>>
>> If I understand correctly, thread 2 is guaranteed to either see q ==
>> null, or to see q.f.x as written by the T constructor?
>
>Yes.
>
>> Now assume I have a static array A of Ts, and a static index variable
>> next_t. Assume final field f now holds an integer index instead of a
>> reference. Effectively I'm just replacing a reference by an integer
>> array index.
>>
>> Assume thread 1b does:
>>
>> o.f = next_t++; // reserve slot.
>> A[o.f] = new T();
>> freeze o.f;
>> q = o;
>>
>> Now if thread 2b sees a non-null q, there is no guarantee that the
>> initialization by T() of A[q.f].x is visible, since A[q.f].x is not
>> reached by following pointers from q.f?
>
>Sad, but true. Otherwise, it gets bad to implement on extremely weak
>memory orders and it kills some potential compiler optimizations.

As Jeremy said, sad but true.

The problem here is that you can treat a reference to an object as a
token that is required in order to prefetch the object.

But an index into an array, and any other data or control dependence,
can't be treated as such a token. For example, we want to allow a
compiler, upon reading a[i], to issue a prefetch for a[i+1].

Alternatively, consider the following (contrived) code for thread 2:

Thread 2:
int x1 = a[1].x;
int i = q.o.f;
int x2 = a[i].x;

It would be hard (and tricky) to argue that transforming thread 2
into the following is illegal:

Thread 2:
int x1 = a[1].x;
int i = q.o.f;
int x2;
if (i == 1) x2 = x1;
else t2 = a[i].x;

Now if q.o.f is 1, thread 2 can see the pre-initialized value of x.

The final field semantics are unfortunately complicated because they
have been very carefully crafted to not cause an compiler or
processor difficulties when a final field is read (except on a few
processors with very weak memory models, such as the Alpha)

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



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