Iterating Collections in Parallel - DZone Java
source link: https://dzone.com/articles/iterating-collections-in-parallel-snippet
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Iterating Collections in Parallel [Snippet]
In this article take a look at how to iterate collections in parallel by setting thread priority and interrupting loop
Join the DZone community and get the full member experience.
Join For FreeWith the standard Java Stream API, we can iterate a collection in parallel thanks to the parallelStream method, but we can't set the priority of the threads that will iterate the collection nor terminate the iteration loop when desired directly on the stream. In this situation, through the underlying configurable BackgroundExecutor the IterableObjectHelper component of Burningwave Core library is able to iterate a collection or an array in parallel executing an action on each iterated item giving also the ability to set the thread's priority and to break the loop when desired:
Collection<Integer> inputCollection =
IntStream.rangeClosed(1, 1000000).boxed().collect(Collectors.toList());
org.burningwave.core.iterable.IterableObjectHelper iterableObjectHelper =
org.burningwave.core.assembler.StaticComponentContainer.IterableObjectHelper;
List<String> outputCollection = iterableObjectHelper.iterateAndGet(
IterationConfig.of(inputCollection)
//Enabling parallel iteration when the input collection size is greater than 2
.parallelIf(inputColl -> inputColl.size() > 2)
//Setting threads priority
.withPriority(Thread.MAX_PRIORITY)
//Setting up the output collection
.withOutput(new ArrayList<String>())
.withAction((number, outputCollectionSupplier) -> {
if (number > 500000) {
//Terminating the current thread iteration early.
iterableObjectHelper.terminateCurrentThreadIteration();
}
outputCollectionSupplier.accept(outputColl -> {
if (outputColl.size() < 125000) {
//Converting and adding item to output collection
if ((number % 2) == 0) {
outputColl.add(number.toString());
}
} else {
//Terminate all threads iteration early (useful also for a find first iteration).
iterableObjectHelper.terminateIteration();
}
});
})
);
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK