如果我在此代码中用挥发性替换原子博物馆,该风险是什么?
我正在阅读JCP 7.2.4,它具有以下代码:
boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
throws InterruptedException
{
ExecutorService exec = Executors.newCachedThreadPool();
final AtomicBoolean hasNewMail = new AtomicBoolean(false); // can we use volatile here?
try{
for(final String host : hosts){
exec.execute(new Runnable() {
public void run(){
if(checkMain(host)){
hasNewMail.set(true);
}
}
});
}
}finally{
exec.shutdown();
exec.awaitTermination(timeout, unit);
}
return hasNewMail.get();
}
本书说:应该使用原子,而不是挥发性,因为内部可运行
可以访问hasnewmail
。
布尔值在有邮件时将其设置为true,而无需考虑其他线程是否设置其值是否为false。
我的疑问是,如果我用挥发性替换这个原子博物馆,那么潜在的风险是什么?任何工作线程都可以将其设置为true(当找到邮件时),所以我是否有可能无法获得正确的值?
I'm reading JCP 7.2.4, it has the following code:
boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
throws InterruptedException
{
ExecutorService exec = Executors.newCachedThreadPool();
final AtomicBoolean hasNewMail = new AtomicBoolean(false); // can we use volatile here?
try{
for(final String host : hosts){
exec.execute(new Runnable() {
public void run(){
if(checkMain(host)){
hasNewMail.set(true);
}
}
});
}
}finally{
exec.shutdown();
exec.awaitTermination(timeout, unit);
}
return hasNewMail.get();
}
The book says: Atomic, not volatile, should be used, as the inner Runnable
could visit hasNewMail
.
Boolean value is set to true when there's mail, without considering if its previous value is true of false, regardless whether other threads are setting its value.
My doubt is, if I replace this AtomicBoolean with volatile, what will be the potential risk? Any working thread could set it to true(when find mail), so is there chance I couldn't get correct value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显然不是;在lambdas或内部类中使用的本地变量必须为有效地最终。
atomicboolean
有效,因为您的变量是对对象的引用 - 并且不会更改。也许在问之前先尝试一下:)
Obviously not; local variables that are used in lambdas or inner classes must be effectively final.
AtomicBoolean
works because your variable is a reference to an object - and doesn't change.Perhaps try it first before asking :)