Chapter 18. Concurrency with Scala Futures and Akka Actors

In Scala, you can still use Java threads:

val thread = new Thread {
    override def run =
        // put your long-running code here ...
        Thread.sleep(100)
        println("Hello, world")
}
thread.start

However, futures and the Actor model are the preferred approaches for concurrency:

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

Actors

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.

Futures

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

The Scala Future is a nice improvement over the Java Thread in several ways:

  • Like the typical use of a Thread, a Future is used when you want to create a little “pocket of concurrency” to run a relatively short-lived task in parallel. ...

Get Scala Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.