是否保证来自 ExecutorService 的线程更新本地声明的并发 hashmap?

Will threads from ExecutorService be guaranteed to update the locally declared concurrent hashmap?

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);
}

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

在此测试方法中,我无法将 "cache" 并发哈希映射声明为 "volatile" 变量,因为它是局部变量而不是实例变量。当代码到达 System.out.println(cache) 行时,它会保证我的主线程将看到由 ExecutorService 线程添加到 "cache" 的所有值吗?

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

您无需关心 poolcache -- 它们实际上是最终变量,因此,它们的值一旦在构造时设置(在您开始任何多-threaded code)不会再改变了。

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