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