What does “volatile” mean in Java?

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

    Small elaboration, but the volatile keyword isn't just for for memory visibility. Before Java ver 1.5 was released the volatile keyword declared that the field will get the most recent value of the object by hitting main memory each time for reads and flushing for writes.

    In the latest Java versions, the volatile keyword says two very important things:

    1. Don't worry about how but know that when reading a volatile field you will always have the most up to date value.
    2. A compiler cannot reorder a volatile read/write as to maintain program order.

    Check it out for more Java volatile examples.

提交回复
热议问题