1

How is the first element determined when findFirst operation is used in a parallel stream?

EDIT

  1. @nullpointer: My intent of question is different from what you have posted as possible duplicate(wherein, the element is doing a job so, there are lot many factors come into play) link and your second link(question) does not talk about parallelism.

  2. ALL: Clarifying on original question, which I admit, should have provided more information - Given an ArrayList of strings(say of a million words as elements) and try to find first element using findFirst, how is first element(say the lookup word be "HelloWorld") determined on parallel(Stream.parallelStream()) execution? I raise this question because as the list is ordered(in which case first encounter in order is returned using findFirst), is parallel execution even considered at first place? If so, the look up word could be anywhere in and any number of instances in a million words/elements and as the list could be divided into many parallel sub-tasks, in this case how is the first element determined?

lupchiazoem
  • 8,026
  • 6
  • 36
  • 42
  • 2
    Possible duplicate of [Java 8 parallelStream findFirst](https://stackoverflow.com/questions/27577337/java-8-parallelstream-findfirst) – Naman Oct 29 '18 at 16:00
  • 1
    Additionally take a look at this as well https://stackoverflow.com/questions/41894173/java-8-findfirst-and-encounter-order – Naman Oct 29 '18 at 16:02

1 Answers1

3

In parallel, we can easily parallelize the upstream operations, but when a result is produced by some subtask, we're not done. We still have to wait for all the subtasks that come earlier in the encounter order to finish. So findFitst if not parallel friendly.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 4
    All parallel terminal operations wait for the completion of all subtasks, as it is crucial to guaranty that no concurrent access to the source data can happen when the initiating thread continues. The difference between `findFirst` and `findAny` is that the latter may send a stop signal to all subtasks once an element has been found whereas the former can only do it for tasks to the right (later in encounter order). – Holger Oct 30 '18 at 08:31