What is the volatile keyword useful for?

前端 未结 23 2613
闹比i
闹比i 2020-11-21 05:32

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that arti

23条回答
  •  抹茶落季
    2020-11-21 05:56

    A variable declared with volatile keyword, has two main qualities which make it special.

    1. If we have a volatile variable, it cannot be cached into the computer's(microprocessor) cache memory by any thread. Access always happened from main memory.

    2. If there is a write operation going on a volatile variable, and suddenly a read operation is requested, it is guaranteed that the write operation will be finished prior to the read operation.

    Two above qualities deduce that

    • All the threads reading a volatile variable will definitely read the latest value. Because no cached value can pollute it. And also the read request will be granted only after the completion of the current write operation.

    And on the other hand,

    • If we further investigate the #2 that I have mentioned, we can see that volatile keyword is an ideal way to maintain a shared variable which has 'n' number of reader threads and only one writer thread to access it. Once we add the volatile keyword, it is done. No any other overhead about thread safety.

    Conversly,

    We can't make use of volatile keyword solely, to satisfy a shared variable which has more than one writer thread accessing it.

提交回复
热议问题