I'm interested in controlling the number of threads used when executing a Java lambda expression in parallel. I'm aware of the solutions presented here, where we put the lambda in a ForkJoin pool to get specific behavior. However, I see nothing in the JavaDoc that indicates a parallel stream must use the ForkJoin framework. So while I could certainly use this solution, I still want to know if there are any guaranteed ways to get this behavior in a portable manner. While I could certainly write some code where in the lambda expression I have to grab a semaphore to run, forcing a specific number of threads to be used - this doesn't actually prevent the excess threads from being created in the first place, and would be an additional overhead that slows everything down (and just ugly).
Asked
Active
Viewed 241 times
1
-
http://stackoverflow.com/questions/24629247/where-does-say-that-javas-parallel-stream-operations-use-fork-join – Sotirios Delimanolis Apr 07 '15 at 00:53
-
http://stackoverflow.com/questions/21163108/custom-thread-pool-in-java-8-parallel-stream – Sotirios Delimanolis Apr 07 '15 at 00:54
-
A lambda expression is just a fancy way of writing an anonymous inner class, hence the thing you need to control must be elsewhere. – Thorbjørn Ravn Andersen Apr 07 '15 at 00:54
-
6No, the mapping to execution policies is not specified. If you want fine-grained control over parallelism, you need to code it yourself; parallel streams will pick a reasonable policy -- but the only guaranteed control you have is to force sequentiality. – Brian Goetz Apr 07 '15 at 01:35
-
Thank you Brian for a concise answer. While I wouldn't call controlling the maximum number of threads particularly fine-grained, I think it would be a good addition in the future. – Raff.Edward Apr 07 '15 at 02:13
-
@Raff.Edward Yes, we are looking into what can be done to provide finer-grained control over execution policies without overly constraining the runtime's ability to make reasonable decisions. – Brian Goetz Apr 07 '15 at 14:44