Threads and futures

You can use threads in Scala, however, there is a better way. You can use threads the same way in Scala, too, but there are alternative approaches. It is yet one other important paradigm shift.

We have seen an example of message-driven concurrency using actors and the Akka framework.

Here is a contrived example, which sums up a list of numbers. The code forks a thread to compute the summation, simulates a delay, and returns the answer to the main thread:

 --------ListSumTask.java-------- import java.util.List; import java.util.concurrent.TimeUnit; public class ListSumTask implements Runnable { private final List<Integer> list; private volatile int acc; // 1 public ListSumTask(List<Integer> list) { super(); this.list = list; this.acc ...

Get Scala Functional Programming Patterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.