What does “volatile” mean in Java?

后端 未结 6 1705
盖世英雄少女心
盖世英雄少女心 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:58

    Volatile is used in many different situations where multiple threads need access to the same variable. Many people not doing multi-threaded/concurrent programming would not be exposed to this. Volatile ensures that the variable is always read from main memory and not from a cache/register version. Volatile is not itself a lock, just because the changes are seen by all threads as soon as they are written does not mean that you can compare and swap in an atomic way. However this feature can be used with other features, like compare-and-swap to build data structures that are thread safe without requiring the user of java's wait-notify semantics which are "heavier".

    you can get more info on this link http://www.quora.com/Threading-in-Java/What-is-the-purpose-of-the-volatile-keyword-in-java

提交回复
热议问题