ExecutorService的线程是否可以保证更新本地声明的并发哈希映射


public void test() {
List<Integer> integers = new ArrayList<>();
for(int i = 0; i < 1000; i++) {
integers.add(i);
}
Map<Integer, Integer> cache = new ConcurrentHashMap<>();
ExecutorService pool = new ForkJoinPool(10);
try {
pool.submit(() -> integers.parallelStream().forEach(integer -> {
String name = Thread.currentThread().getName();
System.out.println("Foo " + name);
cache.put(integer, integer);
})).get();
} catch (Exception e) {
}
System.out.println(cache);
}

我读到您将需要volatile变量,以确保对变量的更新可预测地传播到其他线程。http://tutorials.jenkov.com/java-concurrency/volatile.html#variable-能见度问题

在这个测试方法中,我不能将"缓存"并发哈希映射声明为"易失性"变量,因为它是一个局部变量,而不是实例变量。当代码到达System.out.println(缓存(行时,它能保证我的主线程看到ExecutiorService线程添加到"缓存"中的所有值吗?

是的,您的代码可以正常工作。ConcurrentHashMap保证所有插入的映射将以线程安全的方式发生。

您不需要关心poolcache——它们实际上是最终变量,因此,一旦在构建时(在启动任何多线程代码之前(设置了它们的值,它们就不会再更改了。

可能会让您感到困惑的是,在处理非最终字段时,如果您打算更改它们并确保更改在线程之间正确传播,则可能需要将它们标记为volatile。但如上所述,请注意,在这种情况下,poolcaches的值从未改变。

最新更新