TExcelTAD
Home › Scala › Scala Futures

Scala Futures

A Future[A] represents a value that will be available later — the result of a computation running on another thread, a web request or a database query. Futures let a program start several slow tasks at once and combine their results without blocking a thread while it waits.

Creating a future

A future needs an ExecutionContext — a thread pool that runs its code. For learning and small programs, the global one is fine.

scala · try it yourself
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global

def slowSquare(n: Int): Int =
  Thread.sleep(100)   // pretend this is expensive
  n * n

@main def run(): Unit =
  val f: Future[Int] = Future(slowSquare(7))
  println("future started, doing other work…")
  val result = Await.result(f, 2.seconds)
  println(s"result: $result")
future started, doing other work…
result: 49

Future(...) starts running immediately on the pool. Await.result blocks until the value is ready or the timeout expires.

Note: In real applications you almost never call Await — frameworks accept futures and handle the waiting. In this lesson we use Await at the very end of each program so the output appears in a fixed, predictable order.

Transforming futures

You do not need to wait for a future to describe what should happen to its value. map and flatMap return new futures:

scala · try it yourself
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global

def fetchPrice(item: String): Future[Double] = Future {
  Thread.sleep(50)
  item match
    case "book" => 12.0
    case "lamp" => 30.0
    case _      => 0.0
}

def fetchTaxRate(): Future[Double] = Future(0.2)

@main def run(): Unit =
  val withTax: Future[Double] =
    for
      price <- fetchPrice("lamp")
      rate  <- fetchTaxRate()
    yield price * (1 + rate)

  val label = withTax.map(p => f"Lamp costs $p%.2f")
  println(Await.result(label, 2.seconds))
Lamp costs 36.00

Running tasks in parallel

A for comprehension runs its steps one after another, because each step may depend on the previous one. To run independent tasks in parallel, start them first, then combine:

scala · try it yourself
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global

def task(name: String, ms: Int): Future[String] = Future {
  Thread.sleep(ms)
  s"$name done"
}

@main def run(): Unit =
  val a = task("A", 300)   // all three start right away
  val b = task("B", 300)
  val c = task("C", 300)
  val all: Future[List[String]] = Future.sequence(List(a, b, c))
  println(Await.result(all, 5.seconds))
List(A done, B done, C done)

On a machine with several cores, the three 300 ms tasks overlap and finish in about 300 ms rather than 900 ms. Future.sequence turns a List[Future[A]] into a Future[List[A]] and keeps the original order. Future.traverse(items)(f) does the same while mapping.

Handling failures

If the code inside a future throws, the future fails with that exception. Use recover to turn failures into values, or look at the outcome as a Try.

scala · try it yourself
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Try, Success, Failure}

def loadUser(id: Int): Future[String] = Future {
  if id <= 0 then throw IllegalArgumentException(s"bad id $id")
  s"user-$id"
}

@main def run(): Unit =
  val ok = loadUser(5)
  val broken = loadUser(-1)
  val safe = broken.recover { case e: IllegalArgumentException => s"fallback (${e.getMessage})" }

  println(Await.result(ok, 2.seconds))
  println(Await.result(safe, 2.seconds))

  val outcome: Try[String] = Await.ready(broken, 2.seconds).value.get
  outcome match
    case Success(u) => println(s"got $u")
    case Failure(e) => println(s"failed: ${e.getMessage}")
user-5
fallback (bad id -1)
failed: bad id -1

Useful methods

Method Purpose
Future(expr) run expr asynchronously
Future.successful(v) / Future.failed(e) an already-completed future
map, flatMap, for transform or chain
recover, recoverWith handle failures
Future.sequence, Future.traverse combine many futures
zip combine two futures into a pair
onComplete(callback) react when done (callback runs on the pool)
Await.result(f, timeout) block and get the value (tests, main only)

Avoiding nondeterminism

Futures run on other threads, so println inside them can appear in any order. Keep output deterministic by returning values from futures and printing them in the main thread in a fixed order, as all examples above do.

scala · try it yourself
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global

@main def run(): Unit =
  val jobs = (1 to 5).map(i => Future(i * 10))
  val total = Future.sequence(jobs).map(_.sum)
  val pair = Future.successful("x").zip(Future(42))
  println(Await.result(total, 2.seconds))
  println(Await.result(pair, 2.seconds))
150
(x,42)

Tip: For larger concurrent applications, look at effect libraries such as Cats Effect or ZIO. They build on the same ideas but add cancellation, resource safety and much better testing support.

Test yourself

What does a Future need in order to run its code?

  1. A given ExecutionContext
  2. A database connection
  3. The @async annotation
  4. Nothing

How do you run three independent futures in parallel and collect their results?

  1. Chain them in a for comprehension that creates each one inside
  2. Start all three, then use Future.sequence
  3. Call Await.result on each one before starting the next
  4. Use Future.successful

What happens when code inside a Future throws an exception?

  1. The program crashes immediately
  2. The future completes as a failure holding the exception
  3. The exception is ignored
  4. The future retries