using volatile to create immutable objects

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

using volatile to create immutable objects

Andy Nuss
Lets say I have a class that maps to an int[] by indirection to illustrate my question.  With getters and setters.

class MyIntArrayRef {
     private int[]    ar;

Lets assume that an instance of this object is being used by various threads with synchronized(...), taking all necessary precautions.

Now, lets say one thread knows the the current "ar" member is *not* going to have either all, or some subrange of its data changed, but that the reference itself to the MyIntArrayRef "ar" member will be changed.  So it decides, using synchronized properly on the MyIntArrayRef that is has to created an instance of the following similar class that satisfies the getters interface of MyIntArrayRef:

class MyVolatileIntArrayRef {
      private volatile int[]   ar;     // syntactically, final would compile here, but not work properly?!

      MyVolatileIntArrayRef (int[] ar) {
 = ar;

The ar member passed to its constructor is from the current "ar" of MyIntArrayRef.  Assuming that this object has no setters, neither for "ar" itself, nor any of its data, is it threadsafe without any synchronized methods?  Especially to pass back to threads that have been working with the MyIntArrayRef instance on which this "clone" was based?

My guess is yes.  This "ar" member is volatile, so the JMM says to use a memory barrier when using this class's getters to get elements of the array.  Note that I do not think this would work if the member was declared as just "final", even though for this class, "ar" never changes.  The reason is that the underlying array memory may have already been seen by several cores.

What scares me though is that I've read that on x86 architectures, the volatile read has zero performance cost in some cases, though I've never understood that.  It seems though that you can't have zero performance cost for volatile reads and still have the above use of volatile to create an immutable read only object from an underlying array that has already been seen by several threads.  Can someone explain if the above coding idea works, and if so, how that fits with the volatile implementation on x86?


Concurrency-interest mailing list
[hidden email]