0

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.

  • I would assume that people don't carry a copy of the book with them in their pockets wherever they go. Please show the code your are talking about – Chetan Kinger Dec 27 '17 at 04:23
  • I wish I can delete a question or mark as solved because I just realized why this example isnt broken. – user8829487 Dec 27 '17 at 04:27
  • 1
    You *can* delete your own questions - there's a link under your question for it. (only as long as there are no upvoted answers to it) – Erwin Bolwidt Dec 27 '17 at 04:29
  • I guess since I am on my phone I only see a favorite or edit or share options – user8829487 Dec 27 '17 at 04:31
  • Or you can post an answer to your own question and explain why it's not broken. :) – xiaofeng.li Dec 27 '17 at 04:41
  • That is true, but actually looking back on why I did not think it was broken, I actually take that back. The reason why I thought it was okay was because the object of CellularAutomata is only being used by one thread. However, when calling start it makes N threads which use the Worker object that is created inside of the CellularAutomata object so it is still a field to that object that might not be visible to other threads.. I will have to post a more lengthy explaination when I get home with the actual code – user8829487 Dec 27 '17 at 04:50

0 Answers0