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.

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.”

I’ll write more about this shortly, but yesterday I created a little video of a demo application I call Futureboard. It’s a Scala/Swing application, but it works like Flipboard in that it updates a number of panels — in this case Java JInternalFrames — simultaneously every time you ask it to update.

The “update” process works by creating Scala futures, one for each internal frame. When you select File>Update, a Future is created for each news source, and then simultaneous calls are made to each news source, and their frames are updated when the data returns. (Remember that Futures are good for one-shot, “handle this relatively slow and potentially long-running computation, and call me back with a result when you’re done” uses.)

If you want to create multiple ScalaFutures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.

“Processes interact by one method, and one method only, by exchanging messages. Processes share no data with other processes. This is the reason why we can easily distribute Erlang programs over multicores or networks.”