ExecutorService的线程将保证更新本地声明的并发哈希图吗?

问题描述 投票:0回答:1
    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);
    }

[我读过一点,您将需要具有可变变量,以确保对变量的更新可预测地传播到其他线程。

在此测试方法中,我无法将“缓存”并发哈希图声明为“易失性”变量,因为它是局部变量而不是实例变量。当代码到达System.out.println(cache)行时,是否可以保证我的主线程将看到ExecutorService线程添加到“缓存”中的所有值?

java multithreading java-8 java-stream executorservice
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.