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
在此测试方法中,我无法将“缓存”并发哈希图声明为“易失性”变量,因为它是局部变量而不是实例变量。当代码到达System.out.println(cache)行时,是否可以保证我的主线程将看到ExecutorService线程添加到“缓存”中的所有值?
是的,您的代码可以正常工作。 ConcurrentHashMap
保证所有插入的映射都将以线程安全的方式发生。