What is Scala's approach to concurrency with Futures and Promises?
Answer
Scala's concurrency model separates Future (read-only, result of async computation) from Promise (writable, fulfills a Future). Promise creates a Future and completes it manually: val p = Promise[Int](); val f = p.future; p.success(42) // or p.failure(exception). This is useful when wrapping callback-based APIs. ExecutionContext: defines where Future code runs. ExecutionContext.global uses a fork-join pool sized to available CPUs. Custom: ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(8)). Combining Futures: Future.sequence runs in parallel and collects results. Future.traverse maps then sequences. zip: combine two futures. recover: handle failures. Blocking: Await.result(future, 5.seconds) blocks the calling thread — avoid in production async code. For purely functional async, consider Cats Effect IO or ZIO as more powerful alternatives.
Previous
What is Apache Spark and how does Scala relate to it?
Next
What are Scala's monads and how do they work?