来自文档:
使用易失性变量可以降低内存一致性错误的风险
但这是否意味着有时易失性变量无法正常工作?
奇怪的是它的使用方式 - 在我看来,这是非常糟糕的代码,有时工作有时不工作。我尝试谷歌,但没有找到易失性内存一致性错误的示例。您能推荐一个吗?
问题不在于那么多volatile
工作不可靠。它总是按照它应该的方式工作。问题在于它的工作方式有时不足以满足并发控制。如果你使用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
以确保数据完整性。
欲了解更多信息volatile
vs. synchronized
,我推荐这篇文章管理波动性 http://www.ibm.com/developerworks/java/library/j-jtp06197/index.html作者:布赖恩·戈茨
(*) I realize that the above would be better implemented with AtomicInteger
; it's a contrived example to illustrate a point.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)