Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Concurrency and Futures

Scala Futures and Promises

Write asynchronous Scala code with Future and Promise: execution contexts, map and flatMap, for-comprehensions, parallel futures, error recovery and timeouts.

Waiting is the enemy of throughput. When a program calls a slow database or web service and simply blocks a thread until the answer arrives, that thread can do nothing else. Scala's standard library offers Future[A]: a value of type A that will be available later (or fail). You describe what to do with the result, the work continues in the background, and no thread sits idle in between.

Everything here lives in scala.concurrent. The ideas map directly onto Java's CompletableFuture and JavaScript's Promise.

Creating a Future

SCALA
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val f: Future[Int] = Future {
  Thread.sleep(500)      // pretend to do slow work
  42
}

Future { ... } starts the block on another thread right away and returns immediately. The block runs on an ExecutionContext, which is a thread pool. The line import ...Implicits.global supplies the default pool (one thread per CPU core). In real applications you create dedicated pools for blocking I/O so that slow calls cannot starve CPU-bound work.

In Scala 3 you can also ask for the context with a using clause (see Type Classes and Givens): Future methods take (using ExecutionContext), so any given ExecutionContext in scope is picked up.

A future is always in one of three states: pending, completed successfully, or failed. Once completed it never changes.

Life of a Future

Pending The work is still running.
Success A value is available.
Failure An exception is stored.
1 / 2

Transforming results without blocking

map and flatMap register a function that runs when the future completes, and return a new future:

SCALA
val price: Future[Double] = Future(19.99)

val withTax: Future[Double] = price.map(p => p * 1.2)

def lookupUser(id: Int): Future[String] = Future(s"user-$id")
def lookupOrders(user: String): Future[List[String]] = Future(List("book", "pen"))

val orders: Future[List[String]] =
  lookupUser(7).flatMap(user => lookupOrders(user))

Use flatMap when the next step itself returns a Future; otherwise you end up with a Future[Future[A]]. For longer chains, the for-comprehension reads better:

SCALA
val summary: Future[String] =
  for
    user <- lookupUser(7)
    orders <- lookupOrders(user)
  yield s"$user bought ${orders.mkString(", ")}"

The for-comprehension runs the steps one after the other, because each depends on the previous result.

Running futures in parallel

If two computations are independent, start both futures before combining them:

SCALA
def slow(name: String, ms: Int): Future[String] = Future { Thread.sleep(ms); name }

// Sequential: about 1000 ms
val sequential =
  for
    a <- slow("a", 500)
    b <- slow("b", 500)
  yield a + b

// Parallel: about 500 ms, because both futures are created before the for
val fa = slow("a", 500)
val fb = slow("b", 500)
val parallel =
  for
    a <- fa
    b <- fb
  yield a + b

Other combinators: Future.sequence(listOfFutures) turns a List[Future[A]] into a Future[List[A]]; Future.traverse(items)(f) maps and sequences in one go; Future.firstCompletedOf(...) takes the winner; zip pairs two futures.

flowchart LR
    S["start"] --> A["fa: 500 ms"]
    S --> B["fb: 500 ms"]
    A --> J["combine a + b"]
    B --> J
    J --> R["result after ~500 ms"]

Handling failures

If the code inside a future throws, the future fails and the exception travels along every later step; map and flatMap are skipped. You decide where to deal with it:

SCALA
val risky: Future[Int] = Future(Integer.parseInt("oops"))

val safe1: Future[Int] = risky.recover { case _: NumberFormatException => 0 }
val safe2: Future[Int] = risky.recoverWith { case _ => Future(-1) }  // recover with another Future
val fallback: Future[Int] = risky.fallbackTo(Future(99))

risky.onComplete {
  case scala.util.Success(n) => println(s"got $n")
  case scala.util.Failure(e) => println(s"failed: ${e.getMessage}")
}

recover replaces a failure with a plain value, recoverWith with another Future. onComplete is for side effects at the end of a chain such as logging; its callback result is ignored. Its argument is a Try (see Option, Either and Try). Always handle failure somewhere, or errors vanish silently.

Blocking and waiting

At the very edge of a program (a main method or a test) you sometimes need the final value. Await.result blocks the current thread until completion or a timeout:

SCALA
import scala.concurrent.Await
import scala.concurrent.duration.*

val answer = Await.result(Future(6 * 7), 2.seconds)   // 42

Never call Await inside code that itself runs in a future or a web request handler, because it ties up pool threads and can deadlock. If you must wrap truly blocking code, use scala.concurrent.blocking { ... } so the pool can add a thread.

Promises

A Future is a read-only view. A Promise is the writable side, which you complete yourself, exactly once. Use it to turn a callback-based API into a Future:

SCALA
import scala.concurrent.Promise

def readFileCallbackStyle(path: String)(cb: Either[Throwable, String] => Unit): Unit = ???

def readFile(path: String): Future[String] =
  val p = Promise[String]()
  readFileCallbackStyle(path) {
    case Right(text) => p.success(text)
    case Left(err) => p.failure(err)
  }
  p.future

p.success, p.failure and p.complete(Try) finish the promise; a second attempt throws (use trySuccess if completion may race). p.future is the future that callers see.

A simple timeout helper shows how promises combine futures:

SCALA
def withTimeout[A](f: Future[A], ms: Long): Future[A] =
  val p = Promise[A]()
  val timer = new java.util.Timer(true)
  val task = new java.util.TimerTask {
    def run(): Unit =
      p.tryFailure(new java.util.concurrent.TimeoutException(s"after $ms ms"))
  }
  timer.schedule(task, ms)
  f.onComplete(p.tryComplete)
  p.future

Whichever completes first wins: the timer fails the promise, or the original future completes it. Real projects usually take timeouts from their library (Pekko, cats-effect, ZIO).

Futures are eager

A Future starts running as soon as it is created, and it caches its result. That is different from a lazy description like a Java Supplier. Consequences: creating a future twice runs the work twice, and you cannot retry the same Future value. Wrap creation in a method (def) when you need a fresh run. Effect libraries such as cats-effect IO and ZIO are lazy for this reason; see Actors and Effect Systems.

The same idea in Java and Kotlin

Scala's Future corresponds to Java's CompletableFuture; Kotlin uses coroutines. Neither example below is Scala.

Java Java: CompletableFuture, thenCombine and exceptionally (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: coroutines async and await (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Using Await everywhere, turning async code back into blocking code.
  • Creating dependent futures in the right order but accidentally sequential (the futures-inside-for trap).
  • Ignoring failures. An unobserved failed future is lost; end chains with recover, onComplete or return them to a caller who handles them.
  • Blocking calls on the default pool, which starves other futures. Use a dedicated pool for I/O.
  • Mutating shared vars from several futures. Futures run on multiple threads; see Threads and Synchronization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Future { 42 } do?

    A Future is eager: it is scheduled right away on the execution context, and the caller gets the future without waiting.
  2. 2. When do you need flatMap instead of map on a Future?

    map with a function returning Future[B] gives Future[Future[B]]. flatMap flattens it to Future[B].
  3. 3. How do you run two independent futures in parallel in a for-comprehension?

    Futures start when created. If you create the second inside the for, it only starts after the first finishes.
  4. 4. What is a Promise?

    A Promise lets code complete a Future manually with success or failure, which is how callback APIs are wrapped.

Summary

  • Future[A] is a value that will exist later; it runs eagerly on an ExecutionContext.
  • Transform with map/flatMap/for; start independent futures first to run them in parallel.
  • Handle failure with recover, recoverWith, fallbackTo and onComplete.
  • Avoid Await outside main and tests; use dedicated pools for blocking work.
  • Promise is the writable end, used to adapt callback APIs and build timeouts.

Next: Threads and Synchronization