Synchronizing an object shared across threads, but not accessed concurrently

后端 未结 5 1537
我寻月下人不归
我寻月下人不归 2021-01-16 19:23

Let\'s say I have a shared object with field data. Multiple threads will share a reference to this object in order to access the field. The threads never access

5条回答
  •  无人共我
    2021-01-16 19:40

    You've only told part of the story with the counter. The incrementing part of the counter seems fine -- as Marko points out, there is a HB edge at Thread.start. But who's reading this counter? If it's anybody other than these spawned threads, and you at all care about seeing an up-to-date value, then the field needs to be volatile. If the counter is a long (or double), you need it to be volatile even if you don't care about stale values, because otherwise you could get word tearing.

提交回复
热议问题