Skip to main content

How do I iterate over a collection in multiple threads

In this Q&A, we'll go over how to iterate a collection concurrently using Stream APIs.

Collection interface provides a parallelStream method to allow iteration in multiple threads.  This method uses the common ForkJoin thread pool to execute tasks in multiple threads.    See demo code below:
List<Integer> l = IntStream.range(1,10).boxed().collect(Collectors.toList());
int sum = l.parallelStream().mapToInt(Integer::intValue).sum();

If multiple threads call parallelStream() they will contend for threads in the common thread pool.  See how you can use custom thread pool to resolve the resource contention.

Comments