Java 8 Stream multithreading

13,423

Use parallelStream() to accomplish this. Note that the documentation says that it is "possibly parallel", so there's a chance that you could return a non-parallel stream. I would imagine those cases are rare, but be aware that it is in fact a limitation.

mylist.parallelStream()
      .filter(m -> m.isokay() != null)
      .forEach(m -> m.dosomething()));
Share:
13,423

Related videos on Youtube

BufBills
Author by

BufBills

Updated on September 14, 2022

Comments

  • BufBills
    BufBills over 1 year
    mylist.stream()
          .filter(m -> m.isokay() != null)
          .forEach(m -> m.dosomething()));
    

    For this code, is it running on multiple threads? If not, how can I do it? I want each m.dosomething() to run on seperate threads to speed this work up.

    • Tunaki
      Tunaki over 8 years
      I think you are looking for parallelStream().
    • Solomon Slow
      Solomon Slow over 8 years
      Fyi, .parallelStream() will make use of the ForkJoinPool.commonPool().
    • Louis Wasserman
      Louis Wasserman over 8 years
      Be aware that multithreading can, in many cases, slow your code down. See e.g. this page written by one of the authors of streams.
  • otoomey
    otoomey over 3 years
    Oracle doc specifies "When a stream executes in parallel, the Java runtime partitions the stream into multiple substreams". In this case, "possibly parallel" probably means that you get a sequential stream if it just doesn't make sense to make a parallel one (say if the stream is only one item in size, or threads are currently in short supply)