Stream.parallel() Uses Virtual Threads?

Nathan Reynolds numeralnathan at gmail.com
Fri May 10 17:36:21 UTC 2024


Does/will Stream.parallel() use virtual threads or stay with the Fork Join
common pool threads?

Let's say I have a Stream where the "loop" is I/O bound.  Here is an
example.

list.
   stream().
   parallel().
   map(MyClass::ioBoundOperation).
   ...

In Java 8, 11, and other pre-Java 21 versions, parallel() would use the
Fork Join common pool to execute ioBoundOperation() in multiple threads.
If the list has many elements, then the Fork Join common pool will run out
of threads since there are roughly N threads where N = the number of
vCPUs.  Other parallel streams will then have to wait.  I hope I captured
the situation correctly.

If parallel() uses virtual threads, then multiple parallel streams can
execute and they won't block each other since the number of virtual threads
can be very large.

Let's say parallel() uses virtual threads, would it make sense to always
use parallel()?  I guess there is some small overhead for creating a
virtual thread.  So, processing a small list with short CPU-bound
operations may take more time than it saves.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20240510/8c50deab/attachment.htm>


More information about the loom-dev mailing list