Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection iteration with forEach() in multiple threads or with forEach() and lambdas

Let say I have an array with a thousands independent objects inside. Now I want to pass over each of them and perform the same operation, for instance, change the value of a specific field.

At first glance, there are multiple approaches in Java 8 to such task, for instance:

  1. forEach(); with lambda expression inside:
    itemsArr.forEach(item -> item.setValue("test"));
  2. forEach(); with iterator.
  3. Separate array to a number batches/blocks and deal each batch in a separate thread. For instance: define 2 threads, elements from #0 to 999 will be executed in a thread «A» and the rest in a thread «B».

The final result should be: 100% of array elements should have cared.
What is the optimal approach to such task?

Update: There is a similar question but talks about another aspect, I'm interesting not in different types of loops performance comparison (while, for, forEach) but in a performance comparison of threats vs. lambdas in a task of array traversal?

like image 999
Mike Avatar asked Jan 09 '16 16:01

Mike


People also ask

Is forEach a lambda?

forEach(name -> System. out. println(name)); Since the introduction of Lambda expressions in Java 8, this is probably the most common way to use the forEach method.

What does the forEach () method on Iterable do?

Iterable forEach() The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Is forEach multithreaded Java?

forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.

Is forEach better than for loop Java?

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.


1 Answers

Use a parallel stream, which the JVM will process using multiple threads:

Arrays.stream(itemsArr).parallel().forEach(item -> item.setValue("test"));

Although you seem to have a Collection, not an array, so:

itemsArr.parallelStream().forEach(item -> item.setValue("test"));
like image 74
Bohemian Avatar answered Sep 21 '22 06:09

Bohemian