0

Let's say we have tasks 1-8, and we have 2 threads. Tasks 1-4 are allocated to thread 1 while tasks 5-8 are allocated to thread 2. It is possible to assign an execution sequence, for example, finish task 1 before starting task 2, task 2 will execute based on the output of task 1 for the tasks in the threads?

roland luo
  • 1,561
  • 4
  • 19
  • 24
  • Order of execution is not in your control in parallel streams – Mattia Righetti Apr 16 '21 at 21:18
  • If each task has to complete before the next task can start, then the logic is [`sequential()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#sequential--), the exact opposite of [`parallel()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#parallel--), so why are you trying to use parallel streams? But yeah, sure, you can do `list.stream().parallel().forEachOrdered(...)`. I mean, it's dumb to ask for `parallel()`, just to turn around and ask for *ordered* execution, but whatever... – Andreas Apr 16 '21 at 21:24
  • You have no control over parallel stream execution order or input partitioning. If you need to control this you'll have to do your own coordination and use explicit threads. – Jim Garrison Apr 17 '21 at 00:45

1 Answers1

1

Nope. Java stream parallelism functions in a very specific way which gives it complete control, in particular requiring that it can decide how operations are executed and in what order.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Wouldn't it be possible to use a countdown latch or similar to enforce it, though? – Scratte Apr 16 '21 at 21:29
  • Probably not. How Java streams break up the input, or if they even break up the input _at all_, is chosen by the implementation. You can't guarantee that there will be two different tasks waiting for the latch at all. – Louis Wasserman Apr 16 '21 at 21:31