Future and Promise

A Future[T] is a value of type T that will exist later. The block that computes it runs on a thread of an ExecutionContext, the methods of the future chain the next step without waiting for the first, and a program reads the result at the edge with Await or not at all. A Promise[T] is the other end of a future: the value that completes it.

A future and its result

Future { 21 * 2 } starts the computation at once; map and flatMap describe what happens when it finishes, and Future.sequence turns a list of futures into one future of a list. Await.result blocks the calling thread, which is why a program uses it at the very end and a library does not use it at all:

futures.scala

import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.* @main def futures(): Unit = val answer = Future { 21 * 2 } println(Await.result(answer, 10.seconds)) val combined = answer.map(_ + 1).flatMap(n => Future(n * 2)) println(Await.result(combined, 10.seconds)) val squares = Future.sequence((1 to 5).map(n => Future(n * n))) println(Await.result(squares, 10.seconds)) val zipped = Future(1).zip(Future(2)) println(Await.result(zipped, 10.seconds)) val failed = Future(throw new IllegalStateException("boom")) println(Await.result(failed.recover { case _: IllegalStateException => -1 }, 10.seconds))

scala-cli run --server=false futures.scala

42
86
Vector(1, 4, 9, 16, 25)
(1,2)
-1

Future.sequence answers a Future[Vector[Int]] here, and a single failure in the list would make the whole sequence fail. The chained map(_ + 1).flatMap(...) is one future, not two: the second step is scheduled when the first finishes, and the call site returns immediately. recover handles a failed future with a value, which is what makes a failure part of the type of the chain rather than an exception in a thread nobody watches.

A promise completes a future

A Promise[T] holds a future and completes it once, from any thread. It is the bridge between a callback API and a future: the callback calls success or failure when it has the answer:

promise.scala

import scala.concurrent.{Await, Future, Promise} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.* def work(): Future[Int] = val promise = Promise[Int]() Thread.ofVirtual().start(() => promise.success(6 * 7)) promise.future @main def promises(): Unit = println(Await.result(work(), 10.seconds)) val promise = Promise[String]() val reader = promise.future.map(text => text.toUpperCase) promise.success("from the main thread") println(Await.result(reader, 10.seconds)) val broken = Promise[Int]() broken.failure(new IllegalStateException("no value")) println(Await.result(broken.future.recover { case _: IllegalStateException => 0 }, 10.seconds))

scala-cli run --server=false promise.scala

42
FROM THE MAIN THREAD
0

work() returns the future before the virtual thread has run, and Await waits for the completion the thread performs. promise.success on a promise that is already completed throws, which is why a callback that may run twice checks or uses trySuccess. A promise that is failed answers the failure to everyone who awaits the future, and recover turns it into a value.

Related

Автор статьи: Arthur Isaev