What does “volatile” mean in Java?

后端 未结 6 1720
盖世英雄少女心
盖世英雄少女心 2020-11-29 08:14

We use volatile in one of our projects to maintain the same copy of variable accessed by different threads. My question is whether it is alright to use vo

6条回答
  •  情书的邮戳
    2020-11-29 08:35

    Consider a scenario when two thread (Thread1 and Thread2) are accessing same variable 'mObject' with value 1.

    when a Thread1 runs, it doesn't expect other threads to modify the variable 'mObject'. In this scenario the Thread1 caches the variable 'mObject' with value 1.

    And if the Thread2 modify the value of 'mObject' to 2, still the Thread1 would be refering the mObject value as 1 since it did caching. To avoid this caching we should to declare the variable as

    private volatile int mObject;

    in this scenarion the Thread1 will be getting updated value of mObject

提交回复
热议问题