Do I need volatile for variables of reference types, too?

后端 未结 2 1946
南方客
南方客 2021-01-31 09:23

We often use volatile to ensure that a condition variable can be visible to every Thread.

I see the volatile fields are all primitive typ

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 10:12

    You have to distinguish between the object reference and the actual object.

    • For the reference your field modifier is relevant. When you change the reference to a different object (i.e. reference a different String) the change might not be noticed by a different Thread. If you want to enforce visibility you have to use final or volatile.

    • The actual object on the heap is not affected by the field modifier. Instead how you see each field of this object is determined by its own field modifier according to the same rules (is it volatile or final? If not, visibility for concurrent Threads is not enforced)

    So the answer is: Yes, you have to add volatile or final. Stylistically it would be much better to make the field final, though. It has the same effect Thread-wise but is a stronger statement, too: This field cannot be changed - which is the reason why it can be cached heedlessly by the JVM. And for the same reason it comes with a little performance benefit compared to volatile, Java needs not care whether the field is changes again and does not need to add overhead.

提交回复
热议问题