Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream multithreading

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.

like image 232
BufBills Avatar asked Oct 16 '15 20:10

BufBills


People also ask

Are Java streams multithreaded?

Java 8 introduced the concept of Streams as an efficient way of carrying out bulk operations on data. And parallel Streams can be obtained in environments that support concurrency. These streams can come with improved performance – at the cost of multi-threading overhead.

Is Java 8 stream thread-safe?

In general no. If the Spliterator used has the CONCURRENT characteristic, then the stream is thread-safe. Save this answer.

Is Java 8 stream parallel?

Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially.

Is Java 8 stream faster than for loop?

The short version basically is, if you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.


1 Answers

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()));
like image 195
Makoto Avatar answered Oct 12 '22 14:10

Makoto