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).
- stackoverflow.com/questions/24629247/…Sotirios Delimanolis– Sotirios Delimanolis2015-04-07 00:53:54 +00:00Commented Apr 7, 2015 at 0:53
- stackoverflow.com/questions/21163108/…Sotirios Delimanolis– Sotirios Delimanolis2015-04-07 00:54:00 +00:00Commented Apr 7, 2015 at 0: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– Thorbjørn Ravn Andersen2015-04-07 00:54:11 +00:00Commented Apr 7, 2015 at 0: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– Brian Goetz2015-04-07 01:35:51 +00:00Commented Apr 7, 2015 at 1: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– Raff.Edward2015-04-07 02:13:05 +00:00Commented Apr 7, 2015 at 2:13
| Show 1 more comment