Example of a memory consistency error when using volatile keyword?

后端 未结 2 518
醉梦人生
醉梦人生 2021-02-15 15:47

From docs:

Using volatile variables reduces the risk of memory consistency errors

But this means that sometimes volatile variables

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 16:19

    The issue is not so much that volatile works unreliably. It always works the way it is supposed to work. The problem is that the way it is supposed to work is sometimes not adequate for concurrency control. If you use volatile in the wrong situation, you can still get memory consistency errors.

    A volatile variable will always have any writes propagated to all threads. However, suppose you need to increment the variable among various threads. Doing this(*):

    volatile int mCounter;
    
    // later, in some code that might be executed simultaneously on multiple threads:
    mCounter++;
    

    There is a chance that counter increments will be missed. This is because the value of mCounter needs to be first read by each thread before a new value can be written. In between those two steps, another thread may have changed the value of mCounter. In situations like this, you would need to rely on synchronized blocks rather than volatile to ensure data integrity.

    For more info on volatile vs. synchronized, I recommend the article Managing volatility by Brian Goetz

    (*) I realize that the above would be better implemented with AtomicInteger; it's a contrived example to illustrate a point.

提交回复
热议问题