Chapter 18. Concurrency with Scala Futures and Akka Actors
In Scala, you can still use Java threads:
// put your long-running code here ...
However, futures and the Actor model are the preferred approaches for concurrency:
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” processing.
Are good for processes that run in parallel, live for a long time, and may respond to many requests during their lifetime.
Both futures and actors let you write code at a much higher level of abstraction than threads, and once you’re comfortable with them, they let you focus on solving the problem at hand, rather than having to worry about the low-level problems of threads, locks, and shared data.
Akka and Scala 3
At the time of this writing, Akka has not been ported to Scala 3. Therefore, all the examples in this chapter use the latest version of Scala 2.
Future Scaladoc states, “A
Future represents a value which may or may not currently be available, but will be available at some point, or an exception if that value could not be made available.”
Future is a nice improvement over the Java
Thread in several ways:
Like the typical use of a
Futureis used when you want to create a little “pocket of concurrency” to run a relatively short-lived task in parallel. ...