Synchronizing an object shared across threads, but not accessed concurrently

后端 未结 5 1582
我寻月下人不归
我寻月下人不归 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:45

    the Java Memory Model and bytecode reordering does not guarantee that subsequent thread will see the incremented value of the counter. So if you work with single thread - you don't need to do anything with volatiles, but if several threads may read something from variable - you need to ensure visibility of changes to another threads either with volatile or with syncrhonization/locks.

    Thread.start method imposes the barrier, so visibility is assured - and it may happen that you don't need that volatile stuff. But I would add it anyway.

提交回复
热议问题