在并行流的谓词函数中使用有效的final HashSet
是否安全?
如果不是,有什么好的数据结构可以使用?我没有看到ConcurrentSet
...我想我可以使用ConcurrentHashMap.entrySet()
。
从我所了解的情况来看,即使HashSet没有被修改,最新状态在所有线程中可能仍然无法使用。但也许有一个简单的技巧可以使其可用?
List<Integer> items = Stream
.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.collect(Collectors.toList());
Set<Integer> exclude = Stream
.of(5, 10, 15)
.collect(Collectors.toSet());
List<Integer> filtered = items
.parallelStream()
.filter(num -> !exclude.contains(num))
.collect(Collectors.toList());
ConcurrentHashMap.newKeySet()
。 - Tagir Valeev