4
在并行流的谓词函数中有效使用最终的HashSet
是否安全?parallelStream中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()'。 –