HashSet thread safety in parallel thread

Is it possible to efficiently use the final HashSetin the parallel stream predicate function?

If not, what good data structure to use? I don’t see ConcurrentSet... I suppose I could use ConcurrentHashMap.entrySet().

From what I was able to collect, even if the HashSet is not changed, the last state may not be available in all threads. But maybe there is a simple trick to make it affordable?

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());
+4
source share
1 answer

, , .

+1

All Articles