Futures and parallelism

As i understand futures they provide a way to express concurrency. How fine grained can parallelism be introduced? Suppose i have a list of integers and i want to apply a formula on it using futures, those futures could look like this:

"formula" in pseudo-code:
Y = (x * 2) + (if x < 100 then x else complexOperation(x))

future1 : x * 2
future2: x
future3: complexOperation(x)
future4: if x < 100 then future2 else future3
future5: future1 + future4

parallelizing the list itself would be the most straight forwarded thing to do. That would run future5 (including the underlying futures) on multiple cores.

However would it be possible to parallelize on future2, future3 or future4? When the first value of the list is 1000 and future1 and future2 could complete quickly but the final answer (future5) is still waiting for future3. Then when you can parallelize on future1 this one can already be calculate for the next value in the list.

When you use a thread-pool will the futures that can already be resolved be processed while other futures are still waiting? Can this be done for multiple values? Perhaps you can calculate future1 for the entire list quickly but complexOperation is blocking for some user input. Then in memory you would get a list of partially resolved future5 which can be completed as quickly as possible when future3 stops blocking (this would be the ideal situation to maximize parallelism).

Just not very clear to me what execution model is chosen here and what (and how) can be controlled by code.

1 Like