1

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).

6
  • stackoverflow.com/questions/24629247/… Commented Apr 7, 2015 at 0:53
  • stackoverflow.com/questions/21163108/… Commented 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. Commented Apr 7, 2015 at 0:54
  • 6
    No, 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. Commented 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. Commented Apr 7, 2015 at 2:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.