Iterate a collection using forEach () on multiple threads or with forEach () and lambdas

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

At first glance, there are several approaches to this task in Java 8 , for example:

  • forEach(); with lambda expression inside:

    itemsArr.forEach (item → item.setValue ("test"));

  • forEach(); with an iterator.

  • Divide the array by the number of batches / blocks and process each batch in a separate thread. For example: define 2 threads, items from # 0 to 999 will be executed in thread "A", and the rest in thread "B".

The end result should be: 100% of the array elements should have been taken care of.
What is the best approach to such a task?

Update: There is a similar question , but tells a different aspect, I wonder not compare to compare the performance of different types ( while, for, forEach) but when comparing performance against threats lambdas in the problem of searching an array?

+4
source share
1 answer

Use a parallel thread that 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, therefore:

itemsArr.parallelStream().forEach(item -> item.setValue("test"));
+7
source

Source: https://habr.com/ru/post/1623574/


All Articles