Futures and Promises in Scala
07 Feb 2017The wikipedia article for Futures and promises opens up with this paragraph, which I thought is the perfect definition:
In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete.
In today’s article, I’ll walk you through the creation and management of the future and promise construct in the Scala language.
Execution context
Before continuing with the article, we need to make a special note about the ExecutionContext
. Futures and promises both use the execution context to perform the execution of their computations.
Any of the operations that you’ll write out to start a computation requires an ExecutionContext
as a parameter. These can be passed implicitly, so it’ll be a regular occurrence where you’ll see the following definition:
ExecutionContext.global
is an ExecutionContext
that is backed by a ForkJoinPool.
Futures
We create a Future
in the following ways:
With a future, you set some code in place to handle both the success and fail cases. You use the onComplete
function to accomplish this:
Using a for-comprehension or map/flatMap, you can perform functional composition on your Future
so that adds something extra through the pipeline. In this case, we’re going to prefix the name with a message should it start with the letter “J”:
Blocking
If you really need to, you can make your future block.
Promises
The different between a Future
and a Promise
is that a future can be thought of as a read-only container. A promise is a single-assignment container that is used to complete a future.
Here’s an example.
getNamePromise
has a future that we access through the future
member. We treat it as usual with onComplete
. It knows that it needs to resolve because of the completeWith
call, were we’re telling getNamePromise
to finish the getNameFuture
future.