13.9. Simple Concurrency with Futures

Problem

You want a simple way to run one or more tasks concurrently, including a way to handle their results when the tasks finish. For instance, you may want to make several web service calls in parallel, and then work with their results after they all return.

Solution

A future gives you a simple way to run an algorithm concurrently. A future starts running concurrently when you create it and returns a result at some point, well, in the future. In Scala,it’s said that a future returns eventually.

The following examples show a variety of ways to create futures and work with their eventual results.

Run one task, but block

This first example shows how to create a future and then block to wait for its result. Blocking is not a good thing—you should block only if you really have to—but this is useful as a first example, in part, because it’s a little easier to reason about, and it also gets the bad stuff out of the way early.

The following code performs the calculation 1 + 1 at some time in the future. When it’s finished with the calculation, it returns its result:

package actors

// 1 - the imports
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object Futures1 extends App {

  // used by 'time' method
  implicit val baseTime = System.currentTimeMillis

  // 2 - create a Future
  val f = Future {
    sleep(500)
    1 + 1
  }

  // 3 - this is blocking (blocking is bad)
  val result = Await.result ...

Get Scala Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.