How would you modify a for-each loop to run in parallel and utilize multiple cores/threads in Java?

  • Convert the for-each loop into a traditional for loop and manually distribute loop iterations among threads using a thread pool.
  • Use the Java Stream API and parallelStream() method on the collection to enable parallel execution of the for-each loop.
  • Implement a custom parallelForEach() method that splits the loop iterations among threads using low-level concurrency constructs.
  • Java automatically parallelizes for-each loops; no modification is required.
To run a for-each loop in parallel and utilize multiple cores/threads in Java, you can use the Java Stream API and the parallelStream() method on the collection. Option 2 correctly describes this approach. Option 1 involves manual thread management, Option 3 suggests creating a custom method, and Option 4 is not entirely accurate; Java does not automatically parallelize for-each loops.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *