Scala Concurrency and Futures 2 — Questions and Answers
Question 1: What happens when you call `Await.result` in Scala?
- It cancels the Future
- It blocks the current thread until the Future completes or a timeout elapses (Correct answer)
- It converts a Future to an Option
- It runs the Future synchronously on the same thread
Correct answer: It blocks the current thread until the Future completes or a timeout elapses
`Await.result(future, duration)` blocks the calling thread until the Future completes, returning the value or throwing an exception.
Question 2: What is `flatMap` used for with Scala Futures?
- Flattening a nested collection inside a Future
- Chaining asynchronous operations where each step depends on the previous result (Correct answer)
- Catching exceptions from a Future
- Running two Futures in parallel
Correct answer: Chaining asynchronous operations where each step depends on the previous result
`flatMap` on a Future chains a dependent asynchronous operation, allowing sequential async steps without deeply nested callbacks.
Question 3: How do you recover from a failed Scala Future?
- future.catch(f)
- future.recover { case e: SomeException => defaultValue } (Correct answer)
- future.fallback(defaultValue)
- future.orElse(defaultValue)
Correct answer: future.recover { case e: SomeException => defaultValue }
`recover` applies a partial function to a failed Future, returning a successful Future with a default value if the pattern matches.
Question 4: What is a `for-comprehension` over Futures equivalent to in Scala?
- Running Futures in parallel
- Chaining flatMap and map calls for sequential async composition (Correct answer)
- A blocking await loop
- A parallel for-loop
Correct answer: Chaining flatMap and map calls for sequential async composition
A `for-comprehension` over Futures desugars into `flatMap` and `map` calls, composing sequential asynchronous operations in a readable syntax.
Question 5: What does `Future.successful(value)` create?
- A Future that runs asynchronously
- An already-completed successful Future wrapping the given value (Correct answer)
- A Future that retries on failure
- A Promise initialized with a value
Correct answer: An already-completed successful Future wrapping the given value
`Future.successful(value)` creates an immediately completed Future without scheduling any asynchronous computation.
Question 6: Which Scala library provides actor-based concurrency on top of Futures?
- Scalaz
- Cats Effect
- Akka (Correct answer)
- ZIO
Correct answer: Akka
Akka is the primary actor framework for Scala, providing the actor model for concurrent and distributed systems.
What happens when you call `Await.result` in Scala?