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()));
Related videos on Youtube
Author by
BufBills
Updated on September 14, 2022Comments
-
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 over 8 yearsI think you are looking for
parallelStream()
. -
Solomon Slow over 8 yearsFyi,
.parallelStream()
will make use of theForkJoinPool.commonPool()
. -
Louis Wasserman over 8 yearsBe 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 over 3 yearsOracle 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)