using volatile keyword

后端 未结 6 1583
轮回少年
轮回少年 2020-12-21 02:26

As i understand, if we declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main mem

6条回答
  •  长情又很酷
    2020-12-21 02:50

    testValue is a member variable, so the two threads see two independent copies. volatile is relevant when two or more threads have a reference to the same object.

    Make testValue static and volatile will have an effect. However, you may not (and probably will not) see that effect, as it is highly dependent on timing, scheduling and caching strategies which are out of your (or even the VM's) control. A missing volatile will only rarely have an effect, which makes such bugs very hard to catch. It will only be seen when a thread updates the value and the second thread reads the value and the value is still in the cache in either of the two threads.

提交回复
热议问题