Is calling start() on a object of this class safe? An example from Java Concurrency in practice

℡╲_俬逩灬. 提交于 2019-12-02 07:30:02

You can read the relevant section the Java Language Specification: 17.5. final Field Semantics

The first relevant section (emphasis added by me):

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

The this references is not seen by any other thread before the constructor completes, so it's fine. There is nothing magic about the this reference "escaping" from the constructor; the relevant thing is that no other thread should see it (before the constructor completes).

The next paragraph in the JLS expands on this (emphasis and italics added by me):

The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields.

The danger in allowing this to escape is that it might be seen before it's fully constructed. In this case, that's not an issue because the runnable doesn't execute until start() is invoked, which must be after the constructor completes.

Furthermore, besides the final field guarantees, there are at least two additional happens-before barriers between the assignment of mainBoard and the execution of the runnable. One is the call to Thread.start() by what will be the last thread entering the barrier, which happens-before any action in the started thread. Then there is the actual call to CylicBarrier.await(), which happen[s]-before actions that are part of the barrier action.

So I would say the code is pretty safe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!