Re: JavaMemoryModel: final fields, again

From: Jeremy Manson (jmanson@cs.umd.edu)
Date: Tue Jul 29 2003 - 20:23:03 EDT


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.

On the up side, if you want more guarantees, you can:

1) Set a final field (call it final int [] arr) to point to A, and

2) Make sure Thread 2b never looks at A through any reference other than
arr.

This ensures that you will see the up to date values as of the freeze.
Note that if Thread 2b ever looks at A through the reference A instread of
the reference arr, then you don't have your guarantees anymore.

                                        Jeremy
-------------------------------
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