Future Basics
In this page:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future {
// asynchronous computation
result
}
future.map(x => expression)
Future Basics
A Future[T] represents a value that will become available asynchronously, running its computation on a separate thread managed by an implicit ExecutionContext.
Awaiting a Future's result synchronously (blocking until it completes) requires Await.result(future, timeout), generally reserved for simple scripts, tests, or a program's final step rather than everyday async code. Both scala.concurrent.Await and an ExecutionContext (commonly ExecutionContext.global) must be imported to run and block on a Future this way.
Example: Future Basics
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main extends App {
val future: Future[Int] = Future {
Thread.sleep(50)
21 * 2
}
val result = Await.result(future, 5.seconds)
println(s"Future result: $result")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
ExecutionContextimport, so it fails withCannot find an implicit ExecutionContext. - Calling
Await.resulteverywhere, which blocks the thread and defeats the purpose of aFuture. - Letting the program end before the
Futurefinishes, so its output never appears.
- Implicit parameters and type classes provide flexible behavior.
- Generics and variance describe how types relate.
lazy val,LazyList, andFuturesupport delayed computation and asynchronous work.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: