Is Concurrency In practice listing 5.15 broken?

46 views Asked by At

In JCIP, listing 5.15, Goetz demonstrates a class using CyclicBarrier, but what intrigued me was that inside of the constructor of the class that uses this barrier, he lets the this reference escape by instantiating a new CyclicBarrier.

For other threads, using the object from this class by calling it's start method, couldn't they be seeing bad results since the constructed object they call start on, might not have it's fields mainBoard, barrier and workers visible?

I understand that if things are final, they are guaranteed to be visible to other threads after construction, but that is only if it is properly constructed.

By visible, I mean in terms of safe publication where other threads see the correct values and objects and references that were created durimg construction.

The code also lets the this reference escape when calling new on Worker inside of the constructor.

The more I read, the more I am confused about safe publication and visibility. Can someone clarify how this works?

This seem to contradict what Goetz told us not to do in chapter 3 where he explains why the Holder class is broken by showing what could go wrong in listing 3.15.

I cannot see why this example(listing 5.15) is okay then.

0

There are 0 answers