Skip to Content
Course content

63: scala.concurrent.Future In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're at a busy deli. You walk up to the counter, order a complicated sandwich, and pay. The worker doesn't make you stand frozen at the register until the sandwich is wrapped; instead, they hand you a little plastic buzzer. That buzzer is a promise. It says, "I don't have your food right now, but I'm working on it, and I'll let you know the second it's ready." While you hold that buzzer, you're free to find a table, check your emails, or chat with a friend. You aren't blocked.

In Scala, a scala.concurrent.Future is that buzzer. It's a placeholder object for a value that hasn't been computed yet. Here is how that analogy maps directly to the code:

  • The Order: The block of code inside the Future { ... } block.
  • The Buzzer: The Future[T] instance returned to you immediately.
  • The Kitchen Staff: The ExecutionContext. This is the pool of threads that actually does the heavy lifting in the background. Without a kitchen staff, the order never gets made.
  • The Notification: The callbacks (like onComplete) or transformations (like map) that trigger once the value is ready.

The Engine Under the Hood

I've seen a lot of developers struggle with ExecutionContext because it feels like "boilerplate." It isn't. In Scala, a Future doesn't actually know how to run itself; it needs a strategy for which thread to use. Usually, we use ExecutionContext.global, which is a fork-join pool shared by the whole JVM. In a production app, you'd likely define a dedicated pool for database calls so a slow DB doesn't starve your web server's request threads.

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}

def fetchPrice(item: String): Future[Double] = Future {
  println(s"Fetching price for $item on thread ${Thread.currentThread().getName}...")
  Thread.sleep(1000) // Simulating a slow network call
  if (item == "BrokenItem") throw new RuntimeException("API Down!")
  42.99
}

val priceFuture = fetchPrice("Laptop")

priceFuture.onComplete {
  case Success(price) => println(s"Got the price: $$ $price")
  case Failure(e)     => println(s"Something went wrong: ${e.getMessage}")
}

println("I'm not blocked! I can do other things while the price fetches.")

Chaining Dependencies without Blocking

The real power comes when you have a sequence of events. Say you need to fetch a user's ID from a session, and then use that ID to fetch their order history. If you use map, you end up with a Future[Future[Orders]], which is a nightmare to work with. This is where flatMap saves us. It "flattens" the nested futures into a single one.

Think of flatMap as saying: "Once this first buzzer goes off, use the result to start a second order, and give me a buzzer for that final result."

def getUserEmail(id: Int): Future[String] = Future { 
  // Simulate DB lookup
  "dev@example.com" 
}

def getOrdersForEmail(email: String): Future[List[String]] = Future { 
  // Simulate API call
  List("Order #1", "Order #2") 
}

// Bad: map returns Future[Future[List[String]]]
// Good: flatMap returns Future[List[String]]
val orderHistory = for {
  email  <- getUserEmail(123)
  orders <- getOrdersForEmail(email)
} yield orders

orderHistory.onComplete { 
  case Success(list) => println(s"User orders: $list")
  case _             => println("Error occurred")
}

Handling a Crowd of Futures

What happens when you need to trigger five different API calls and wait until all of them are finished? You don't want to chain them sequentially with flatMap because that would take five times as long. You want them to run in parallel.

Future.sequence is your best friend here. It takes a List[Future[T]] and turns it into a Future[List[T]]. It's like ordering five different sandwiches for your friends; you don't care which one finishes first, you just want a notification when the whole tray is ready.

val items = List("Laptop", "Mouse", "Keyboard")
val allPricesFutures = items.map(item => fetchPrice(item)) // List[Future[Double]]

val combinedFuture = Future.sequence(allPricesFutures) // Future[List[Double]]

combinedFuture.onComplete {
  case Success(prices) => println(s"Total cost: ${prices.sum}")
  case Failure(e)      => println(s"One of the fetches failed: ${e.getMessage}")
}

One final word of caution: avoid Await.result whenever possible. Calling Await is like standing at the deli counter and refusing to move until your sandwich is done, blocking everyone behind you. It defeats the entire purpose of using Future. Always prefer transformations (map/flatMap) or callbacks.




📋 Practical Task

Build a Parallel Currency Converter

You need to build a small utility that fetches the exchange rate for a base currency (USD) against multiple target currencies (EUR, GBP, JPY, CAD) simultaneously.

Requirements:

  • Create a function fetchExchangeRate(currency: String): Future[Double]. To simulate a real API, use Thread.sleep(500) and return a random double between 0.5 and 1.5.
  • Create a list of target currencies: List("EUR", "GBP", "JPY", "CAD").
  • Use Future.sequence to trigger all requests in parallel.
  • Once all rates are returned, use a map or for-comprehension to calculate the total value of 100 USD converted across all those currencies (i.e., 100 * sum of all rates).
  • Print the final result using onComplete.
  • Ensure your main thread doesn't exit before the Future completes (you may use a Thread.sleep(2000) at the very end of your main method for this purpose).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.