[concurrency-interest] can a core see semi-constructed objects in array before the publishing act

thurstonn thurston at nomagicsoftware.com
Mon Jun 10 01:07:44 EDT 2013

Andy Nuss wrote
> Hi,
> I have a volatile array "ar" of objects.  I wish to add tuples of N
> objects to the array with the following idiom:
> void publish (Object obj1, Object obj2, Object obj3, Object obj4)
> {
>      lock();                                      // atomic lock
>      Object[] ar = this.ar;
>      int pos = calculatepos(...);
>      ar[pos+1] = obj2;
>      ar[pos+2] = obj3;
>      ar[pos+3] = obj4;
>      ar[pos] = obj1;                         // if the reader sees null,
> the tuple is empty to him at that moment
>      this.ar = this.ar;                       // java.util.concurrency
> uses this idiom to publish
>      unlock();
> }
> ...
> Andy

Why not define a Tuple class:
class Tuple
final Object partOne
final Object partTwo
final Object partThree
final Object partFour

Tuple(Object partOne, Object partTwo, Object partThree, Object partFour)
     this.partOne = partOne;
     this.partTwo = partTwo;
     this.partThree = partThree;
     this.partFour = partFour;

then define ar as Tuple[] ar;

this would obviate any visibility problems for the readers, i.e. when
iterating over /ar/, they would either see null or a reference to a Tuple
with the fully *initialized* four parts even if the part Objects were not
strictly immutable (not to mention it's more O-O) (this assumes of course
that the parts are not mutated after constructing the Tuple)

as far as "effectively final", we use that term to refer to classes that
have fields that are only set once, but for a variety of reasons it may not
be possible/advisable to set in the constructor (cf: DCL).  I've always
thought that would be a useful annotation for a field; although I'm
guessing, I would think that the VM might be able to make useful
optimizations from that?

and finally, does this.ar = this.ar serve any purpose?  I would have thought
that the JVM (maybe even javac?) could simple elide that, regardless of *ar*
being volatile.  I was unaware that j.u.c. relied on that.
Also would have thought that there is no difference between 
Object lar = this.ar
this.ar = this.ar and
this.ar = lar

View this message in context: http://jsr166-concurrency.10961.n7.nabble.com/can-a-core-see-semi-constructed-objects-in-array-before-the-publishing-act-tp9691p9713.html
Sent from the JSR166 Concurrency mailing list archive at Nabble.com.

More information about the Concurrency-interest mailing list