Synchronizing an object shared across threads, but not accessed concurrently

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

    Studying the entire JLS chapter on the Java Memory Model is highly recommended – mandatory, in fact – for anyone doing concurrency in Java. Your case, specifically, is covered in JLS, 17.4.4:

    "An action that starts a thread synchronizes-with the first action in the thread it starts."

    This means that for your first scenario you don't need volatile. However, it would be good practice to have it anyway to be robust to future changes to the code. You should really have a good reason not to have volatile, which would be only in the case of an incredibly high read rate (millions per second at the very least).

提交回复
热议问题