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

后端 未结 2 1922
南方客
南方客 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:24

    You add volatile keyword to tell the compiler that its bound to change. so that all threads re-confirm that their local cached copy is same as that of original one, if there are changes it updates it. and you find it usually with Primitives because usually primitive values are incremented or decremented etc by different threads. but Object, especially List will never change since its just a reference to the Object. if you are assigning different objects to the same variable, at run-time then you may do..

提交回复
热议问题