CodeToLive

Scala Futures & Async

Learn asynchronous programming with Scala Futures.

Basic Future

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val future = Future {
  // Long running computation
  Thread.sleep(1000)
  42
}

future.onComplete {
  case Success(value) => println(s"Got value: $value")
  case Failure(ex) => println(s"Error: ${ex.getMessage}")
}

Future Composition

val future1 = Future { 1 + 1 }
val future2 = Future { 2 + 2 }

val combined = for {
  a <- future1
  b <- future2
} yield a + b

combined.foreach(println)  // Prints 6

Error Handling

val riskyFuture = Future {
  if (math.random() > 0.5) throw new Exception("Boom!")
  "Success"
}

val safeFuture = riskyFuture.recover {
  case e: Exception => s"Recovered from ${e.getMessage}"
}

Async/Await

import scala.concurrent.Await
import scala.concurrent.duration._

val result = Await.result(future, 2.seconds)
println(result)  // 42

Promise

import scala.concurrent.Promise

val promise = Promise[Int]()
val future = promise.future

// In another thread
new Thread {
  override def run(): Unit = {
    Thread.sleep(1000)
    promise.success(42)
  }
}.start()

future.foreach(println)  // Eventually prints 42
← Back to Tutorials