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


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


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

An introduction to Scala/Akka Actors (Actors and Concurrency)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is the introduction to Chapter 13, “Actors and Concurrency.”

In Scala you can still use Java threads, but the “Actor model” is the preferred approach for concurrency. The Actor model is at a much higher level of abstraction than threads, and once you understand the model, it lets you focus on solving the problem at hand, rather than worrying about the low-level problems of threads, locks, and shared data.

One way that functional programming helps with concurrency

I’ve read a lot of irrational claims about how functional programming helps with concurrency, but if a compiler can do what this says, at least it’s a clear, rational example of how FP can help with concurrency. It’s taken from an article titled, Functional programming for the rest of us.

On the Scala Future, and semantics

In programming, semantics can be important. While in many cases I don’t care too much how developers name classes and variables, in some cases monikers can cause problems. (Perhaps even in that sentence.)

An Akka Actors Ping-Pong example

Here’s a 30-second “ping-pong” demo using Akka Actors:

The source code

If you want the source code, you can get it from the GitHub link shown at the end of this post. First, here’s a quick description of it.

The code is in two files, PingPong.scala and PingPongPanel.scala.

PingPong.scala contains three actors: