deterministic

“Pure functional programming is programming with mathematical functions” alvin August 6, 2017 - 2:13pm

“Pure functional programming is programming with mathematical functions.”

~ Erik Meijer

Simple concurrency with Scala Futures (Futures tutorial)

Table of Contents1 - Problem2 - Solution3 - Run one task, but block4 - Run one thing, but don’t block, use callback5 - The onSuccess and onFailure callback methods6 - Creating a method to return a Future[T]7 - How to use multiple Futures in a for loop8 - Discussion9 - A future and ExecutionContext10 - Callback methods11 - For-comprehensions (combinators: map, flatMap, filter, foreach, recoverWith, fallbackTo, andThen)12 - See Also13 - The Scala Cookbook

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 13.9, “Simple concurrency with Scala Futures.”

Back to top

Problem

You want a simple way to run one or more tasks concurrently in a Scala application, including a way to handle their results when the tasks finish. For instance, you may want to make several web service calls in parallel, and then work with their results after they all return.

Back to top

Solution

A Future gives you a simple way to run an algorithm concurrently. A future starts running concurrently when you create it and returns a result at some point, well, in the future. In Scala, it’s said that a future returns “eventually.”