Future Basics
In this page:
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.
Note: Blocking with Await.result is mainly appropriate for scripts, tests, or a program's very last step -- production async code usually chains callbacks instead.
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: