What is the volatile keyword useful for?

前端 未结 23 2605
闹比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:57

    There are two different uses of volatile keyword.

    1. Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
    2. Reduces the risk of memory in-consistency errors.

    Prevents JVM from reading values in register, and forces its value to be read from memory.

    A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:

    while (busy) {
        /* do something else */
    }
    

    The testing thread will continue when another thread turns off the busy flag:

    busy = 0;
    

    However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

    Reduces the risk of memory consistency errors.

    Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a "happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

    The technique of reading, writing without memory consistency errors is called atomic action.

    An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.

    Below are actions you can specify that are atomic:

    • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
    • Reads and writes are atomic for all variables declared volatile (including long and double variables).

    Cheers!

提交回复
热议问题