使用volatile关键字时出现内存一致性错误的示例? [英] Example of a memory consistency error when using volatile keyword?

查看:90
本文介绍了使用volatile关键字时出现内存一致性错误的示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档:

使用易失性变量可降低内存一致性错误的风险

Using volatile variables reduces the risk of memory consistency errors

但这意味着有时可变变量不能正常工作吗? 奇怪的使用方式-我认为这是非常糟糕的代码,有时无法正常工作.我尝试使用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.

有关volatilesynchronized的更多信息,我建议文章 管理波动性 ,作者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关键字时出现内存一致性错误的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆