gpt4 book ai didi

java - 为什么 Goetz 不再在代码 list 7.20 中使用 volatile boolean 呢?

转载 作者:行者123 更新时间:2023-12-01 07:01:20 24 4
gpt4 key购买 nike

以下是 Brian Goetz 的 Java Concurrency in Practice 中 list 7.20 中的代码:

public class CheckForMail {
public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final AtomicBoolean hasNewMail = new AtomicBoolean(false);

try {
for (final String host : hosts)
exec.execute(new Runnable() {
public void run() {
if (checkMail(host)) hasNewMail.set(true);
}
});
} finally {
exec.shutdown();
exec.awaitTermination(timeout, unit);
}
return hasNewMail.get();
}

private boolean checkMail(String host) { // Check for mail return
false;
}
}

提到这段代码,Goetz 说“使用 AtomicBoolean 而不是 volatile boolean 值的原因是,为了从内部 Runnable 访问 hasMail 标志,它必须是最终的,这将阻止修改它”(第 158 页)。

为什么它必须是最终的?难道你不能把它变成一个非最终的 boolean 变量吗?

最佳答案

However why does it have to be final? Couldn't you just make it a non final boolean volatile?

hasNewMail 需要从内部 Runnable 访问,正如 Goetz 所说。这是一个内部类的实例。在 Java 的最新版本中,内部类访问词法封闭方法的局部变量时需要变量“有效地最终”。我认为 Goetz 是在需求更强烈的时候写的:变量确实是final。对于此目的,“有效最终”和“最终”之间的区别并不重要,但是,无论哪种方式,都无法修改变量。

还要注意,Goetz 代码中的 AtomicBooleanfinal。它本身无法修改,但存储在其中的值可以修改,这就是程序的工作原理。

关于java - 为什么 Goetz 不再在代码 list 7.20 中使用 volatile boolean 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48143117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com