Execution contexts

A Future does not choose a thread; it asks an ExecutionContext for one. That type is the interface between the concurrency of the program and the threads that run it: a global pool that fits most programs, a pool of a known size for a server, and a separate pool for the calls that block.

The global context

ExecutionContext.Implicits.global is the pool a small program imports and forgets. It is a work-stealing pool sized from the processors of the machine, which is why the program below never prints a thread count: that number depends on the computer it runs on:

global.scala

import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.* @main def global_context(): Unit = val squares = Future.sequence((1 to 3).map(n => Future(n * n))) println(Await.result(squares, 10.seconds)) println(Await.result(Future(2).map(_ + 1), 10.seconds))

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

Vector(1, 4, 9)
3

A global pool is right for short CPU work and wrong for a blocking call: a pool with as many threads as the machine has processors loses one of them for the whole duration of every blocking read. The next program gives its futures a pool of their own, which is also the place where a test can put a single thread and make a race impossible.

A pool of your own

ExecutionContext.fromExecutor wraps a JDK executor, here a fixed pool of two threads. The block of a future that blocks is marked with blocking, which tells the global pool to add a thread if it needs one; a pool of your own is sized by you instead, and it is shut down when the work is done:

pool.scala

import java.util.concurrent.Executors import scala.concurrent.{Await, ExecutionContext, Future, blocking} import scala.concurrent.duration.* @main def fixed_pool(): Unit = val pool = Executors.newFixedThreadPool(2) given ExecutionContext = ExecutionContext.fromExecutor(pool) val tasks = (1 to 4).map { n => Future { blocking(Thread.sleep(20)) n * 10 } } println(Await.result(Future.sequence(tasks), 10.seconds)) pool.shutdown() println(pool.isShutdown)

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

Vector(10, 20, 30, 40)
true

Four tasks of twenty milliseconds on two threads are two rounds, and the results come back in the order of the list because Future.sequence keeps it, not because the tasks ran in that order. pool.shutdown() lets the running tasks finish and refuses new ones; a program that forgets it keeps a non-daemon thread alive and never exits.

When no context is in scope

The context is a using parameter of Future, so a file that imports neither the global one nor a pool does not compile. The message names the missing type and the import that adds it:

no_context.scala

import scala.concurrent.Future @main def no_context(): Unit = println(Future(1))

mkdir -p out
scalac -color:never -d out no_context.scala 2>&1; echo "exit status: $?"

-- [E172] Type Error: no_context.scala:4:19 ------------------------------------
4 | println(Future(1))
  | ^
  |Cannot find an implicit ExecutionContext. You might add
  |an (implicit ec: ExecutionContext) parameter to your method.
  |
  |The ExecutionContext is used to configure how and on which
  |thread pools asynchronous tasks (such as Futures) will run,
  |so the specific ExecutionContext that is selected is important.
  |
  |If your application does not define an ExecutionContext elsewhere,
  |consider using Scala's global ExecutionContext by defining
  |the following:
  |
  |implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
  |
  |The following import might fix the problem:
  |
  | import scala.concurrent.ExecutionContext.Implicits.global
  |
1 error found
exit status: 1

The message is long because the fix has two forms, and it is worth reading to the end once: a using parameter in the method, or the import of the global context. A library that returns futures takes the context as a parameter for the same reason the message gives: the caller decides where the work runs, and the library cannot know whether blocking is allowed there.

Related

Article author: Arthur Isaev