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
- The Scala Cookbook
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.”
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.
This statement from the book, Learning Concurrent Programming in Scala, sums up the appeal of functional programming in languages like Scala.
Martin Odersky: “There is no silver bullet for all concurrency issues.” From the book, Learning Concurrent Programming in Scala.
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.
Another great quote from this article on The Downfall of Imperative Programming.
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.)
I’ll write more on this as time permits, but for now, I’ll just say that semantics in computer programming can be very important, and the term
Future caused me quite a bit of grief. I wish it had been named something else, such as
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: