Discuss Scala's capabilities for writing asynchronous non-blocking code.
Instruction: Explain the mechanisms and techniques available in Scala for writing asynchronous non-blocking code, with examples.
Updated
A Future[T] represents eventual success or failure. Its map, flatMap and for composition let a caller arrange dependent work without synchronously waiting for the result. An ExecutionContext schedules the work; it does not make the body non-blocking or guarantee parallel execution. Wrapping a blocking database call in Future { ... } moves the blocking to a worker thread.
This complete Scala 3 example starts two small computations before composing their results:
import java.util.concurrent.Executors
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.*
@main def futureExample(): Unit = {
val executor = Executors.newFixedThreadPool(2)
given ExecutionContext = ExecutionContext.fromExecutor(executor)
try {
val first = Future { 20 }
val second = Future { 22 }
val total = for {
a <- first
b <- second
} yield a + b
assert(Await.result(total, 5.seconds) == 42)
} finally {
executor.shutdown()
}
}
Await deliberately blocks only this standalone program's entry point so the example can check its result and finish. In a server request or event loop, return or compose the future instead. These two futures are already started before the comprehension; constructing the second inside the first one's flatMap would make its start dependent on the first's success. This example has only a fixed amount of small work; its fixed thread pool has an unbounded queue and is not a complete overload-control design. Fixed thread pool contract Futures and execution contexts
For I/O, prefer an asynchronous client that already returns a future. Isolate unavoidable blocking work on an appropriate executor with bounded admission and a lifecycle owner. A blocking hint can inform a supporting execution context; it is not a universal cure for exhaustion. Do not wait on work that needs the same exhausted pool.
A Promise is the single-assignment producer side of a future and can bridge a callback API. Use tryComplete, trySuccess or tryFailure when duplicate completion is possible; they report whether completion won. Promise completion Return an existing future directly when no adaptation is needed. Handle expected failures with deliberate recovery and preserve unexpected ones. A timeout on a wait does not cancel the underlying computation, and standard futures do not provide general cancellation or backpressure. Those requirements need explicit support in the surrounding API or effect/stream library.