18
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.

3
  • 5
    I think you are looking for parallelStream(). Commented Oct 16, 2015 at 20:28
  • 3
    Fyi, .parallelStream() will make use of the ForkJoinPool.commonPool(). Commented Oct 16, 2015 at 20:49
  • 4
    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. Commented Oct 16, 2015 at 21:22

1 Answer 1

25

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()));
Sign up to request clarification or add additional context in comments.

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.