Table of Contents
- Run one task, but block
- Run one thing, but don’t block, use callback
- The onSuccess and onFailure callback methods
- Creating a method to return a Future[T]
- How to use multiple Futures in a for loop
- A future and ExecutionContext
- Callback methods
- For-comprehensions (combinators: map, flatMap, filter, foreach, recoverWith, fallbackTo, andThen)
- See Also
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
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.”
Here’s a little example of how exceptions work with Scala Futures, specifically looking at the
onComplete ‘Failure’ case.
In this example I start three Futures that run for different lengths of time, and the shortest-running
Future throws an exception:
There are a number of ways to work with Scala Futures, and I provide examples of those approaches in the Scala Cookbook.
If you’re new to Futures, a fun exercise is to try to determine what happens in your code when you use a certain technique. For instance, when you look at the following Scala source code, what do you think it will print?