HashSet在parallelStream中的线程安全性

4

在并行流的谓词函数中使用有效的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());

2
没问题,那应该可以。 - Louis Wasserman
关于线程安全的集合,您可以使用 ConcurrentHashMap.newKeySet() - Tagir Valeev
1个回答

1
只要您不在并行线程中修改设置,按照您的示例描述的方式使用应该是完全安全的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接