Futures & Promises 2.10 January 9, 2013
Callbacks, the abiliby to reference a code fragment and pass it as argument to to another function is very popular and its used throught the application layers. I can be blocking or non blocking(used for IO, event processing). In scala async callbacks are done using futures and futures were implemented in many of the frameworks build ontop of scala.
In scala 2.10 there is a new implementation of Futures and adds the implentation of Promises.
The goals of this new implemention are:
1. To have a single implenation of this functionality (not one per framework).
2. To make this implementaion efficient and composable.
3. To take advantage of scala's power to make futures a more powerfull tool.
So what are Futures & Promises
Futures - Read only. Placeholder that may hold the result of a computation or the exception in case of a failure. "It is in effect immutable" which means you can pass it around to other threads whithout fear of it getting corrupted.
Futures have hooks for the expected outcomes:
onComplete, onSuccess, onFailure
These callbacks are executed independently and without a specific order between them (at least in the default implementation).
You should be carefull with the amount of pending futures as they become available for garbage collection only once they are executed. So you should see a memory during the time a lot of them are pending.
Promises - Writable once, scala framework takes care of this so you dont have to. A promise completes its future by providing the return value or the exception in case of failure. For a promise p the correcponding future is p.future.
You can use p success value or p failure exception to complete p.future. If the promise was already set, an exception is thrown, for that reason there are the p trySuccess value and p tryFailure exception methods which will complete the promise only it if is not already completed.
Some more reading material, whith a lot more details:
And here is a complete example for simple use of futures and promises: