[concurrency-interest] final field/constructor visibility (cf. CyclicBarrier)

Yuval Shavit yankee.sierra at gmail.com
Sun Sep 28 11:43:17 EDT 2014

This is somewhat related to a discussion I started here on synchronized
constructors (specifically, why they're not allowed). In particular:

The short of it is that your code is _still_ not safe in the face of unsafe
publication. Yes, you establish HB relationships between the lock/unlock in
the constructor and other lock/unlocks -- but you still haven't guaranteed
that the constructor is seen first, as un-intuitive as that sounds. Some
thread could see (for instance) a getter invoked before the constructor. In
that case, the default value happens-before the getter, which
happens-before the constructor. Clearly, that's not helpful, but it's valid
according to a strict reading of the JMM.

To be safe even in the face of unsafe publication, you'd need to not just
establish just any old HB edge, but more precisely to ensure that the
constructor happens-before everything else. One way to do that could be:

    volatile boolean ctorFinished;

    CyclicBarrier(int parties) {
        // lock/unlock, set this.count and this.parties...
        ctorFinished = true;

    int getCount() {
        while (!ctorFinished) {} // spin, wait for the ctor to finish on
the instantiating thread
        // etc

On Sun, Sep 28, 2014 at 3:18 AM, thurstonn <thurston at nomagicsoftware.com>

> But why not as I referenced?
> <code>
> CyclicBarrier(int parties)
>     this.lock.lock();
>     this.count = parties;
>     this.lock.unlock();
>     this.parties = parties;
> </code>
> Is it just somehow unappealing/ungainly (not often you see self-lock
> acquisition in a constructor - can't say I like it that much)?
> Of course you're right about safe publication,and I should have referenced
> the fact that it's only unsafe in the face of improper publication.
> Still I think it's valuable to have j.u.c objects be "either null or
> multi-thread safe" where possible (e.g. ReentrantLock)
> --
> View this message in context:
> http://jsr166-concurrency.10961.n7.nabble.com/final-field-constructor-visibility-cf-CyclicBarrier-tp11306p11309.html
> Sent from the JSR166 Concurrency mailing list archive at Nabble.com.
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140928/fba65288/attachment-0001.html>

More information about the Concurrency-interest mailing list