I (a newbie) am testing my concepts about Scala's Futures and the right patterns to use them.
The premise
Scala's futures are blocks of code to be executed asynchronously. So, the main thread creates one or more such futures, installs onSuccess() [note: equally applicable to OnComplete/onFailure] callbacks and proceeds. The callbacks are executed as and when the futures complete their runs.
Presumably, these callbacks generate results which are supposed to be used by the main thread. The results are stored in a Try[T] container, with a write-once/read-many constraint. The main (or any other thread but that is not the point) decide when to peak in the container and collect the results for further processing.
Whichever discussion/blog/API I have laid my eyes on so far, mentions the fact that main thread doesn't have to wait: it can carry on doing its own thing, allowing the futures to be executed in parallel and be ready with the result.
Question
But my question is: in the simplest case, where it has finished doing whatever it is doing, the main thread will have to wait for the callbacks to finish, will it not? And, because there is no interruption mechanism provided which can indicate that the future has finished execution, the main thread has no option but to 'wait' (possibly with a time-limit) for the result to be ready? In other words, in an application, where futures are employed, a wait is ultimately unavoidable, isn't it?
Note
I understand that we can chain the futures, using combinators or Promise (and there are other patterns too), to avoid this issue altogether. But, I am trying to clarify my concept that under certain cases, using futures doesn't obviate the need to wait for them to finish.
Is it too elementary a question? Is it showing a big void in my understanding?
play framework
there is no "main thread". You could also check in main thread if future is completed and that perform some actions without waiting. – seniaFuture
is the ultimate consumer of it. That is not necessarily so. However, whatever computation does consume that value must wait for it, of course, but even that need not be done by waiting. As you observe, it can be delivered via one of the completion handlers. It is in fact possible to write systems that neverAwait
aFuture
, but rather do everything asynchronously. – Randall Schulzawait
or something there would be no need. I think the confusion you have here is probably because you expect that JVM will only shutdown when main thread exists? – Jatin