13.9. Simple Concurrency with Futures
You want a simple way to run one or more tasks concurrently, 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.
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.
The following examples show a variety of ways to create futures and work with their eventual results.
Run one task, but block
This first example shows how to create a future and then block to wait for its result. Blocking is not a good thing—you should block only if you really have to—but this is useful as a first example, in part, because it’s a little easier to reason about, and it also gets the bad stuff out of the way early.
The following code performs the calculation
1 + 1 at some time in the future. When it’s
finished with the calculation, it returns its result:
// 1 - the imports
// used by 'time' method
// 2 - create a Future
// 3 - this is blocking (blocking is bad)