Scala Promises
A Promise is a handle that lets you complete a Future by hand. It separates making a Future from deciding its result.
A Promise completes a Future by hand
The Promise and its Future are made as a pair. success fills the Future, and Await reads the filled value.
import scala.concurrent.{Future, Await, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
@main def main(): Unit =
val p = Promise[Int]()
val f = p.future
p.success(7)
val result = Await.result(f, 5.seconds)
println(result)A Promise can carry a computed value
The value given to success can come from an expression. Here it is 3 times 4.
import scala.concurrent.{Future, Await, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
@main def main(): Unit =
val p = Promise[Int]()
val f = p.future
p.success(3 * 4)
val result = Await.result(f, 5.seconds)
println(result)One completed Promise serves every waiter
Two waits on the same Future give the same completed value. The Promise is completed only once.
import scala.concurrent.{Future, Await, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
@main def main(): Unit =
val p = Promise[Int]()
val f = p.future
p.success(9)
val first = Await.result(f, 5.seconds)
val second = Await.result(f, 5.seconds)
println(first)
println(second)Example
import scala.concurrent.{Future, Await, Promise}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
@main def main(): Unit =
val p = Promise[Int]()
val f = p.future
val total = 80 + 10
p.success(total)
val result = Await.result(f, 5.seconds)
println(result)Key points
- Promise: a handle for completing a Future by hand.
- Pair: p.future is the Future that readers wait on.
- Complete: p.success(7) fills the Future with 7.
- Wait: Await.result on p.future gives the completed value.
- Once: after a Promise is completed, its value does not change.
In this example, a Promise and its Future are made as a pair. The total 80 plus 10 is worked out first, success fills the Future with 90, and Await reads that value for printing.
Note
use a Promise when the result arrives from somewhere else, not from inside a Future body.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does p.success(7) do?