问题描述
来自文档:
但这意味着有时可变变量不能正常工作吗?奇怪的使用方式-我认为这是非常糟糕的代码,有时无法正常工作.我尝试使用Google,但没有找到带有volatile的示例内存一致性错误.你能提出一个吗?
But this means that sometimes volatile variables don't work correct?Strange how it can be used - for my opinion it is very bad code that sometimes work sometimes not. I tried to Google but didn't find example memory consistency error with volatile. Could you please propose one?
推荐答案
问题不仅仅在于volatile
运行不可靠.它始终以应有的方式工作.问题是它的工作方式有时不足以进行并发控制.如果在错误的情况下使用volatile
,仍然会出现内存一致性错误.
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.
volatile
变量将始终将任何写入传播到所有线程.但是,假设您需要在各个线程之间增加变量.这样做:
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++;
有可能错过计数器的增量.这是因为mCounter
的值需要先被每个线程读取,然后才能写入新的值.在这两个步骤之间,另一个线程可能已经更改了mCounter
的值.在这种情况下,您需要依靠synchronized
块而不是volatile
来确保数据完整性.
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.
有关volatile
与synchronized
的更多信息,我建议文章 管理波动性 ,作者Brian Goetz
For more info on volatile
vs. synchronized
, I recommend the article Managing volatility by Brian Goetz
我意识到,使用AtomicInteger
可以更好地实现上述功能;这是一个说明问题的人为例子.
I realize that the above would be better implemented with AtomicInteger
; it's a contrived example to illustrate a point.
这篇关于使用volatile关键字时出现内存一致性错误的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!