[concurrency-interest] a question about concurrent safe access

Brian Goetz brian at quiotix.com
Mon Sep 19 10:35:10 EDT 2005


> say I have a pointer ( reference) to an object ( A). This reference is 
> changed to point at object B. I have threads that concurrently are using 
> that reference to get the object it points at. I dont want to 
> synchronize the usage of the reference. Is it safe to do so, i.e. if I 
> dont use a lock and I dont declare the reference volatile will I always 
> get object A or B or do I have a risk of getting "dirty" inconsistent 
> pointer , i.e. is assigning a pointer always atomic  ?

The assignment of the _value_ of the pointer is atomic.  However, that 
does not mean this idiom is safe, because this does not promise anything 
about the object _pointed to_.  It is possible to see inconsistent 
values for the fields of the pointed-to object unless it is immutable.

Just writing a shared pointer is a form of "unsafe publication".

Example:

class Sum {
   // Invariant: a+b = sum
   public int a, b, sum;

   Sum(int a, int b) {
     this.a = a;
     this.b = b;
     this.sum = a+b;
   }
}

public static Sum sum;

Thread A:  sum= new Sum (3,4);

Thread B:  Sum mySum = sum;

At the end of this, Thread B could see sum have any of the following 
values for (a,b,sum):

   (0,0,0) *
   (0,0,7)
   (0,4,0)
   (3,0,0)
   (3,4,0)
   (3,0,7)
   (0,4,7)
   (3,4,7) *

The ones labeled with * are the only ones which are "consistent".



More information about the Concurrency-interest mailing list