In this chapter you will learn
-
how to declaratively design concurrent program flows
-
how to use lightweight virtual threads (fibers)
-
how to safely store and access data from different threads
-
how to process a stream of events asynchronously
“ We know the past but cannot control it. We control the future but cannot know it. ”
—Claude Shannon
Threads, threads everywhere
So far in the book we’ve been focusing on sequential programs: each program consisted of a sequence of expressions that were evaluated one by one using a single execution thread, usually connected to a single core.
We won’t be focusing on cores (or CPUs) in this chapter. We will focus on having multiple threads. Note that multiple threads can still run on a single core. The operating system switches between different threads to make sure everyone gets a chance to progress.
This mode of operation is very useful in practice. It’s far easier to understand a program when it’s sequential. It’s easier to debug, and it’s easier to make changes. However, we’ve witnessed some great improvements in the hardware area over the last decade, and right now the majority of consumer hardware is armed with multiple cores. The software needed to follow suit, and that’s how multithreaded programming became the way to develop modern applications. Our programs need to do many things at once to deliver results for our users faster. They need to use many threads to preprocess data in the background or split computations into multiple parallel chunks. When we implement concurrent programs, they usually look like this.
Entering the multithreaded world means that we no longer can debug and understand our applications with the level of confidence we had with single-threaded sequential ones. The mainstream, imperative approach doesn’t help here, either. Having to deal with shared mutable states accessed by multiple threads, which additionally need to synchronize with each other, avoiding deadlocks and race conditions, turns out to be very hard to get right. On top of this, we still need to deal with all the problems we had in the sequential world, such as error handling and IO actions. Concurrency adds another layer of complexity. Does FP have some things that can help? Let’s see and compare them with all the most popular imperative approaches to concurrency as we go.
We deal with a race condition when a result depends on the sequence or timing of other uncontrollable events, such as which thread finishes first.
Declarative concurrency
Functional programming has some ideas about how to handle concurrency differently. The main assumption still holds: immutable values and pure functions are always the same, no matter whether they are used and accessed by a single thread or multiple threads. It turns out these FP ideas make the concurrent programs easier to write! They take away the whole category of complexity problems related to shared mutable state and impure functions.
THIS IS BIG!
Writing concurrent programs is much easier when we can only deal with immutable values and pure functions.
An additional benefit is that we will still develop programs that consist of sequences of expressions executed on different threads. Hence, everything we have learned so far will be applicable to multithreaded environments as well ! The only difference is that our pure functions will be evaluated concurrently. The rest remains the same: they will be evaluated as a part of programs defined using familiar IO values. Our concurrent programs will still be defined declaratively as lazily evaluated values! *
* Remember that in FP we want to be as declarative as possible (i.e., focus on what, not how).
In this chapter we will show just a single approach to functional concurrency. It’s very practical and can be used in several functional languages besides Scala. Note, however, that this area is still undergoing rapid, dynamic development, so make sure to focus mostly on how pure functions, immutable values, and multiple threads can be used together to create user-friendly, responsive apps that are easy to read, change, and maintain. At the end of this chapter we will also point out some additional approaches that use these concepts in a different way (in Scala and other languages).
We will develop an application that gathers tourist “check-ins” in cities around the world and provides an up-to-date ranking of cities.
Requirements: City rankings
-
The program needs to process a stream of check-ins from people around the world (a Stream[IO, City] value will be provided).
-
The program should allow getting the current top three cities’ ranking (ranked by check-ins), while the check-ins are still being processed.
Let’s start with some basic modeling. The model of a City is just a newtype . Additionally, we will need a product type that keeps a current check-ins counter for a given City .
> | object model opaque type City = String
object City {
def apply(name: String): City = name
extension (city: City) def name: String = city
}
case class CityStats(city: City, checkIns: Int)
}
import model._ |
## Sequential vs. concurrent
Before we move on to the full-blown multithreaded application, we’d like to show you that requirements for the check-ins ranking application, even though they scream _multithreading_ , can be implemented on a single thread, using the sequential approach and functional techniques you already know! This will also help us make sure we understand what needs to be done in general and why we may still need concurrency (and multiple threads) to develop this application as required. Moreover, this is old but proven advice: start simple and iterate from there. Let’s start simple.

When constrained to the sequential, single-threaded approach we need to interleave implementations for both requirements.

This process is called **batching** . We gather a batch of `n` items, process them, update the progress in some way (still sequentially), and then we proceed to do the same for the next batch of `n` items. Sometimes we may use a different way of batching (e.g., time-based), but the idea remains the same. By updating the ranking (which is a measure of progress from the user perspective) after each batch we give a feeling of _live_ updates (users may get a feeling that things are happening at the same time), and it’s fine in some scenarios. However, there is a hidden trade-off there, which we’ll discuss in further detail after you implement this version.
Updating the ranking step may be an output IO action, like storing in a database, printing to the console, storing using an API call, or showing on an UI.
## Coffee break: Sequential thinking 
Requirements: City rankings
1. The program needs to process a stream of check-ins from people around the world (a **`Stream[IO, City]`** value will be provided).
2. The program should allow getting the current top three cities’ ranking (ranked by check-ins), while the check-ins are still being processed.
Your first task is going to be a mix of some functional design, IO, and stream handling, which will all serve well to recap the material from the last few chapters and prepare you to handle concurrency issues.
You are free to come up with a design of your own. If you are stuck, remember that you can start with a small function first (e.g., function that gets a `Map` of check-ins and returns a `List` of the top three cities).
**Implement a function that processes each check-in one-by-one and produces a current ranking** after processing each check-in element:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit]
```
To make things simpler, we are going to simulate “updating the ranking” as just printing the current version of a ranking on the console using `println` . Here’s a stream that you can use to test your solution.
> | val checkIns: Stream[IO, City] = Stream(
City("Sydney"),
City("Sydney"),
City("Cape Town"),
City("Singapore"),
City("Cape Town"),
City("Sydney")
).covary[IO] ①① covary transforms a Stream of pure values into a stream of IO-based values, so we don’t have to wrap them in IO.pure manually. checkIns is a Stream of six programs that will return cities when executed. The programs will be evaluated in the given order. |
In a sense, it’s going to be a batching algorithm with a batch size of n = 1. We will show how to use bigger batches after the exercise, but you are free to explore the APIs and think about the solution on your own.
Calling the **`processCheckIns`** function should return a program, which, once executed, prints seven ranking updates (including the first, empty ranking) to the console and returns a `Unit` value, ().
```erlang
processCheckIns(checkIns).unsafeRunSync() ①
List()
List(CityStats(City(Sydney),1))
List(CityStats(City(Sydney),2))
List(CityStats(City(Sydney),2), CityStats(City(Cape Town),1))
List(CityStats(City(Sydney),2), CityStats(City(Singapore),1), CityStats(City(Cape Town),1))
List(CityStats(City(Cape Town),2), CityStats(City(Sydney),2), CityStats(City(Singapore),1))
List(CityStats(City(Sydney),3), CityStats(City(Cape Town),2), CityStats(City(Singapore),1))
→ ()
```
① We “ `unsafeRunSync` " this value here for testing purposes. Normally, we operate solely on `IO` values and “ `unsafeRunSync` " only once outside of the functional core.
If you have problems coming up with a solution, have a look at `scan` , `foreach` , the `Map` type, and its `updated` function (or `updatedWith` ?).
Go through the `Stream` API to find them.
## Coffee break explained: Sequential thinking 
There are many ways you could have approached this problem. The following is one of them. When confronted with a blank page, it’s always hard to figure out where to start. Fortunately, our business requirements are pretty clear: each city has an integer indicating the current number of check-ins, and we need to return a ranking of the top three cities back.
`City`
a newtype (zero-cost wrapper) around a `String` value
> | def topCities(cityCheckIns: Map[City, Int]): List[CityStats] = { cityCheckIns.toList
.map(_ match {
case (city, checkIns) => CityStats(city, checkIns)
})
.sortBy(_.checkIns)
.reverse
.take(3)
} |
`CityStats`
a product type of two types: `City` and `Int` (check-ins number)
We transform the `Map` into a `List` of tuples, then transform each tuple to a `CityStats` value, sort by check-ins, reverse to get the descending order, and `take` the maximum of the three first elements.
Another thing we need to do is to look at what’s given to us and what options it provides. In our case, we have a `Stream[IO, City]` —a stream of `City` values, each indicating a single check-in. We know streams have many combinators, and going through a stream and accumulating values is a pretty common use case. And indeed, we can use `scan` to accumulate check-ins as a `Map[City, Int]` !
> | checkIns.scan(Map.empty[City, Int])((cityCheckIns, city) => { val newCheckIns = cityCheckIns.get(city) match {
case None => 1
case Some(checkIns) => checkIns + 1
}
cityCheckIns.updated(city, newCheckIns)
}) |
This code does its job, but `Map` has an `updatedWith` function that takes both a key and a function from `Option` to `Option` , which we can use to make this code more concise. See the final solution (below) where we used the `updatedWith` function that behaves the same way.
Since `scan` emits a value of our accumulator each time it’s computed, we now have a stream of `Map` s, which we can `map` using the `topCities` function we wrote and then show ( `println` ) the ranking to the user.
> | def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = { checkIns
.scan(Map.empty[City, Int])((cityCheckIns, city) =>
cityCheckIns.updatedWith(city)(_.map(_ + 1).orElse(Some(1)))
)
.map(topCities)
.foreach(IO.println)
.compile.drain
} |
After the `map` function we have a `Stream` of `List[City]` , which is what our users are interested in. We can then use the `foreach` function that takes an `IO` value describing a program that needs to be executed for each element of the stream. We pass a function, which is a more convenient way of writing this:
`foreach(ranking => IO.delay(println(ranking)))`
## The need for batching
The first version of the check-ins processing app looks good, but unfortunately, it does not scale. The more cities in the accumulator `Map` , the longer the sorting process takes; therefore, more and more computation power will go into sorting. And since we only use one thread, the more time a single piece of functionality takes, the less time the other ones will get. In our case, more check-ins (cities) will make the accumulator large. So far, we used small streams to test our implementation. Let’s notch it up a bit. Try to run your function on a stream of hundreds of thousands check-ins.
Our large stream of check-ins This is a stream of 600,003 (600\_003) cities which we will use in the chapter to show how concurrency helps create responsive programs even in the presence of large datasets. \*
> | val checkIns: Stream[IO, City] = Stream(City("Sydney"), City("Dublin"), City("Cape Town"), City("Lima"), City("Singapore"))
.repeatN(100_000)
.append(Stream.range(0, 100_000).map(i => City(s"City $i")))
.append(Stream(City("Sydney"), City("Sydney"), City("Lima")))
.covary[IO] |
A stream of five cities: Sydney, Dublin, Cape Town, Lima, and Singapore is repeated 100\_000 times, resulting in a stream of 500\_000 elements. Then we append another 100\_000 randomly named cities. Finally we append a small stream of three cities to make sure we know what the top of the ranking should look like.
> | processCheckIns(checkIns).unsafeRunSync() ... // a long, long time (several minutes) |
\* You can write big numbers like that in Scala, so they are more readable. Underscores are ignored by the compiler.
Quick exercise 
Since we are waiting for your program to finish running, can you tell us what the final TOP3 ranking should be? This will test your streaming knowledge because you need to decode both the big `checkIns` stream above and the current sequential implementation. Additionally, it should make you feel better when you get the correct answer before the computer (how often does that happen?).

**Our implementation does not scale!** We need some **real batching** , not `n = 1` , but something bigger—let’s say `n = 100_000` .
Answer:
See next page.
## Batching implementation
To make our implementation more scalable, we will need yet another stream combinator, namely, `chunkN` . It takes a number `n` and transforms `n` elements into a single collection-like element, which is then emitted.

That’s how we can quickly replace computing the ranking `600_000` times (once for each check-in) to computing it only six times (once for every `100_000` check-ins):
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
checkIns
.scan(Map.empty[City, Int])((cityCheckIns, city) =>
cityCheckIns.updatedWith(city)(_.map(_ + 1).orElse(Some(1)))
)
.chunkN(100_000)
.map(_.last)
.unNone
.map(topCities)
.foreach(IO.println)
.compile.drain
}
```
Each check-in is processed and produces an accumulator `Map` , as was the case before. However, in this version, we batch (chunk) the accumulators into batches of `100_000` elements and then take only the `last` accumulator from a batch to compute the ranking.
The ranking is still presented using a `println` .
```
List(CityStats(City(Sydney),100002), CityStats(City(Lima),100001), CityStats(City(Singapore),100000))
```
Now, it will finish processing pretty quickly, printing the final ranking in the process (the last one from seven printed lines).
Now you can check whether you got it right and taunt your computer if you did.
Batching trade-offs
We won’t be focusing on batching in this chapter, but please remember that it’s always a possibility and may prove to be better for some cases. Sometimes, if you can get away with writing a sequential solution to a business problem, it will end up being a simpler one as well. However, there are always some trade-offs to consider. In our case: | |
- The bigger the batch size in this sequential example, the lower the frequency of ranking updates (users get an update only every `n` check-ins). It may be OK for some cases but will definitely not be for others.
- There are some corner cases that need to be handled. For example, what happens when there are `590_000` check-ins and then 5 minutes of silence? `90_000` check-ins will sit there, not processed, waiting for the remaining `10_000` to be able to compute a new ranking. Therefore, you’d need to add some additional time-based constraints, which is totally doable but adds complexity nonetheless. Again, this may or may not be OK in a given case.
## The concurrent world
The context has been set. We have implemented the requirements for a check-in processor in a sequential way, using batching to make it good enough in terms of performance and scalability. But that’s as long as we can possibly go constrained to a single thread. When we allow ourselves to use more than one thread, a brand new world of opportunities emerges. We no longer need to decide how much computation time each functionality needs. We can give each of the two functionalities its own thread, and if our program gets assigned two CPUs, they will do their work simultaneously. In the case where we had many threads at our disposal, we could use `n` threads to process batches of check-ins in parallel and a single thread that updates the ranking.

This, in turn, exposes us to a problem of shared mutable state because the ranking functionality needs access to the current checkIns Map , which is updated by the check-in processing functionality. So all execution threads will need to access the same memory address, which additionally changes over time. This is the concurrent shared mutable state in action, and we will try to deal with it using functional programming techniques. | |
Note that the amount of threads we want to create is strictly dependent on the amount of CPU resources we have at our disposal. When you have two CPUs for the whole application, creating one hundred threads to process check-ins may not be a good idea. There are lots of variables that play a role here, so the best advice in such cases is this: benchmark your implementation and optimize based on results. To make things simpler **we will use two threads—** one for check-ins and one for ranking—throughout the rest of the chapter, but it’s going to be implemented in a way that makes it safe even when there are more threads.
Using two threads doesn’t really expose us to the shared mutable state problem because each variable is mutated by a single thread. However, we will increase the number of check-in threads at the end of the chapter to prove that the FP solution works fine in such cases as well.
Using multiple threads is faster because the ranking is being updated continuously in a separate thread in parallel with the check-ins’ processing threads. However, this improvement comes at a cost! (More on that soon.)
## The concurrent state
Let’s first give some background on how we deal with threads and concurrent state in some imperative languages, based on Java.
```
var cityCheckIns = new HashMap
(); ①
Runnable task = () -> { ②
for(int i = 0; i < 1000; i++) {
var cityName = i % 2 == 0 ? "Cairo" : "Auckland";
cityCheckIns.compute(cityName,
(city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
}
};
new Thread(task).start();
new Thread(task).start();
```
① We create a mutable `HashMap` that models our concurrent state. Then, we create a `Runnable` that adds 500 check-ins to each `Cairo` and `Auckland` .
② Then, we start two threads that use the same `Runnable` , so we expect that both `Cairo` and `Auckland` will have `1000` check-ins each in the `HashMap` once they finish processing. But they won’t. What will be the result, in your opinion? \*
We will use the setup above to introduce the imperative approaches to solving our concurrent state problem. We will use a combo of diagrams and small Java snippets when necessary, but we won’t show a full-blown imperatives solution in the book. | * (Answer at the bottom.) |
Fully working examples are available in the book’s companion source code.
More generally, we will discuss **synchronization primitives** . These are tools implemented in operating systems, languages, and libraries that help us synchronize the execution of multiple threads. This usually means one of the two following things:
- _Synchronizing the access to a common resource_ —For example, a file, socket, in-memory variable, database connection
Also known as the critical section problem
- _Synchronizing (or coordinating) the execution order of multiple threads—_ For example, making sure a thread starts executing only after another thread produced something or waiting for something to happen before launching a set of threads
Also known as the thread signaling/thread interaction problem
There are many various primitives used in the industry, and we can’t cover them all here. We will just briefly identify the most common approaches and then show how some of them are very useful in composition with FP concepts.
Have you ever used a `Semaphore` or a `CountDownLatch` ?

Q Is it even possible to be able to mutate a value in memory and still write pure functions?
A Yes! Note that even though we explicitly started using immutable values at the beginning of the book, we have still been able to write so many different applications, and they all have been modeling data that changes over time. We have tools that use similar approaches in the concurrent world as well, but before we introduce them, let’s see what are the most popular solutions to the concurrent state in modern languages.
Answer: Much fewer than 1000 check-ins. There is also a chance that one of the threads throws an exception.
## Imperative concurrency
All the imperative concurrency examples we will show in this section are written in Java.
When you manually create two threads that modify the same mutable variable, you will most likely end up with nondeterministic behavior. Each thread needs to read the current value, compute something, and then store the updated value. In the meantime, the other thread could have written an updated value, which would now be overwritten. That’s why we got fewer than 1,000 check-ins in the previous example.

Some implementations, including the one we showed, may additionally _sometimes_ cause a `ConcurrentModificationException` . This will pop up from time to time, nondeterministically, depending on how operations from both threads are ordered. Therefore, in a nutshell, just creating more than one thread and not caring about the concurrent access problem guarantees we will encounter random behavior or random failure—all bets are off. We need to guard the access to a common resource, which in this case is a mutable in-memory variable. Let’s see which synchronization primitives are the most popular.
Monitors and locks
Monitors are synchronization primitives that control the access to a given resource by making sure only a single thread uses it at a time. They also keep track of all other threads that want to use (or acquire) the resource and notify them once it becomes available. They use locks ( _mutexes_ ) internally. In its most basic form, a monitor works like this:

```
var cityCheckIns = new HashMap();
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
var cityName = i % 2 == 0 ? "Cairo" : "Auckland";
synchronized (cityCheckIns) { ①
cityCheckIns.compute(cityName,
(city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
}
}
};
```
① When we enter the `synchronized` block, no other thread can enter it, and it waits until we exit. This means that all read–write sequences done by the `compute` function are ordered.
There are lots of other options that could help us achieve this result. For example, in Java you also have a `Lock` interface. We treat all such options as similar, imperative mechanisms because you need to explicitly provide `lock` and `unlock` statements to use them.
The actor model
In the actor model, we use actors as primary concurrency units, instead of using threads directly. Actors **encapsulate** state, and the only way we can interact with an actor and its state is by **sending and receiving asynchronous messages** . These messages are buffered in an inbox and processed by the actor instance one by one, making sure only a single thread has access to its state at a given time. Actors can create more actors—forming actor hierarchies—which help in dealing with potential failures. Here’s the example implemented using the actor model in Java (and the Akka library):

```scala
class CheckInsActor extends AbstractActor { ①
private Map cityCheckIns = new HashMap<>(); ②
public Receive createReceive() { ③
return receiveBuilder()
.match(StoreCheckIn.class, message -> {
cityCheckIns.compute(message.cityName,
(city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
}).match(GetCurrentCheckIns.class, message -> {
getSender().tell(new HashMap<>(cityCheckIns), null); ④
}).build();
}
}
```
① You can’t create the `CheckInsActor` class using a new statement. You can create it using a special function that returns an `ActorRef` , which only enables you to send messages. The state is safely stored inside the actor.
② We show this implementation in Java because it belongs to the imperative world. More in the book’s code repository.
③ The `receive` method is called sequentially for each incoming message. Here we expect two kinds of messages, represented by two classes: `StoreCheckIn` and `GetCurrentCheckIns` .
④ `tell` sends a message to an actor.
Thread-safe data structures
Using the actor model to safely modify a `HashMap` may seem like overkill because we also can use mutable data structures that can be accessed (both reading and writing) by multiple threads at once without damaging the consistency of the data it holds: “thread-safe” data structures. One example is Java’s `ConcurrentHashMap` :

Note that, while thread-safe data structures work very well, they are specialized and can’t easily be used in many scenarios. Actors are much more versatile.
```
var cityCheckIns = new ConcurrentHashMap();
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
var cityName = i % 2 == 0 ? "Cairo" : "Auckland";
cityCheckIns.compute(cityName,
(city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
}
```
## Atomic references
We won’t be using any of the imperative synchronization primitives in our functional programs because they are all based on mutability and providing “recipes.” Using them would mean that we couldn’t write pure functions, and we’d lose all the benefits that come with them: trustworthy signatures, readability, and risk-free refactoring.
There is a far better option that we will use and which is already available in many mainstream languages, including Java. **An atomic reference** is a very practical mechanism that makes use of the **compare-and-set** (or _compare-and-swap_ , or _CAS_ ) operation. This operation behaves deterministically in a multithreaded environment without needing to use locks, even internally, as is the case with thread-safe data structures (some people describe such mechanics as _“lock-free”_ ).
We could use these mechanisms in functional programs by wrapping them in some `IO` s. This is always a possibility if you really need to use some impure code in your applications. However, there are better options we’d like to introduce.
```java
var cityCheckIns = new AtomicReference<>(new HashMap()); ①
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
var cityName = i % 2 == 0 ? "Cairo" : "Auckland";
var updated = false;
while(!updated) {
var currentCheckIns = cityCheckIns.get();
var newCheckIns = new HashMap<>(currentCheckIns);
newCheckIns.compute(cityName, (city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
updated = cityCheckIns.compareAndSet(currentCheckIns, newCheckIns); ②
}
}
};
```
① `AtomicReference` provides the `compareAndSet` function that takes two values: the first is what we think is the current value stored inside the atomic reference, and the second is the value we’d like to store there. The function returns `true` if the value was successfully replaced and `false` if the current value we provided is not valid (it was changed by some other thread in the meantime).
② If `compareAndSet` returns `false` , we need to repeat the whole process of getting the current value and updating it. Note that we are required to use a copy of the `HashMap` , because `compareAndSet` uses reference equality. We used the copying technique earlier in the book, just before introducing immutable values, which are a perfect fit for `AtomicReference` and `compareAndSet` !
This operation is very versatile and can be used to implement other synchronization primitives. Additionally, if you are familiar with database locks, this is exactly the technique that is used to implement optimistic locking (all updates are accepted when your application proves that it knows the most up-to-date version of given data). It turns out that this technique is very universal and readable. It perfectly suits the functional programming paradigm , even in Java, which has a functional alternative to the compareAndSet + imperative loop technique used above, called updateAndGet , which takes a function. | |
```
cityCheckIns.updateAndGet(oldCheckIns -> {
var newCheckIns = new HashMap<>(oldCheckIns);
newCheckIns.compute(cityName,
(city, checkIns) -> checkIns != null ? checkIns + 1 : 1);
return newCheckIns;
});
```
This code can safely replace the body of the `for` loop above.
THIS IS BIG!
In FP, programmers tend to use atomic references a lot when creating concurrent programs.
## Introducing `Ref`
We have just discussed some approaches to both the concurrent access problem and thread coordination. We will now show functional tools that enable us to use many threads and solve the concurrent access problem.
To write concurrent programs, you don’t need to create locks, wait for them, or notify other threads when you are finished. You also don’t need to settle for mutable data structures. In FP, we model everything as immutable values. We will now show a **functional atomic reference** that will allow us to safely store a changing value using just pure functions and `IO` values.
**`Ref[IO, A]`** **is an immutable value that represents an asynchronous concurrent mutable** \* (and thus, side-effectful) reference to an immutable value of type `A` (essentially, a wrapper around an `AtomicReference` ) + .
\* We will talk about synchronous versus asynchronous computation more later in the chapter, but for now it means that the thread that updates the reference doesn’t actively wait nor block.
+ Remember how we used Java’s `AtomicReference` ? It required us to use immutable values. We used copies, but real immutable values are far easier to use!
Note how similar this description is to the way we described the `Stream[IO, A]` type, which is an immutable value that represents a stream of side-effectfully generated values of type `A` and how similar it is to `IO[A]` , which is an immutable value representing a side-effectful program that, when executed, will produce an `A` value.
Concurrency primitives trade-offs
All of the primitives we describe in this chapter can help us write correct multithreaded applications. Without them, all bets are off and we **can be sure** that the data will quickly become inconsistent. Making sure all changes to our data are consistent is not free though. It comes at a cost, which needs to be properly managed. Debugging possible deadlocks, livelocks, and contention problems will become the bread and butter for a programmer of a multithreaded application.
Performance is usually heavily affected. For example, we use more CPU cycles when using _compare-and-swap operations_ to update highly contended memory address. Sometimes we make users wait for the up-to-date results longer. All of these concerns are usually not essential from the business perspective, unless they visibly affect the user experience. However, returning correct results is always an essential concern. We don’t want any race conditions or indeterministic outputs, but we still want all the pure function benefits (for the same arguments, you always get the same result!) and easier maintenance. We need to design applications that are responsive enough and return correct results.
We discuss low-level programmer-centric tools in this chapter, but remember you have also some user-facing concepts at your disposal. For example, eventual consistency means that the ranking users get is a correct one but may be from the past, and they will eventually get the current one when they repeat the process. This is a valid approach to some problems!
## Updating `Ref` values
`Ref[IO, A]` is a value representing a concurrently accessible mutable reference. I know it’s a mouthful, but let’s appreciate how consistent it is with all the previous concepts we discussed. We use immutable values to represent everything and make it simple to write programs using pure functions. What kind of pure functions can we use with `Ref` ? There are many built-in options, but we will focus on a single one, which is a functional alternative to the compare-and-swap (CAS) operation. R `ef[IO, A]` provides an `update` function that has the following signature:
THIS IS BIG!
We model concurrently accessible shared mutable states as immutable values.
```sql
def update(f: A => A): IO[Unit]
```
Do you see the CAS operation there? We just need to provide a function from A to A and we are done! This is how we mutate a reference to the concurrently accessible value of type A . We won’t need anything else. The function we pass will get the current A and will need to return the new A back. The Ref type internals take care of everything, including a possibility of value A being changed by another thread. If the value A changes in the meantime, our function f will be called again with the changed value A . Note how this behavior is consistent with how other CAS implementations, including AtomicReference we discussed earlier, work. Most importantly, the update function returns an IO value back , which means that we just get a description of a side-effectful program that changes the reference to a different immutable value . Nothing is executed until somebody, outside of the functional core, executes this IO value (which most likely is as a part of a bigger IO value). | |
For example, say we have a value of type `Ref[IO, Int]` , which represents a concurrently mutable reference to an integer, which is `0` at the beginning, and we run two threads. (1)
(1) We will learn how to create `Ref` values very soon. Focus on the usage for now.
 (2)
(2) We will learn how to create threads as a part of programs described by `IO` values later in the chapter. Until then, let’s use `unsafeRunSync` to prove the properties of `Ref` values.
The mutable reference will always have value `3` when both threads conclude. That’s how we mutate using only pure functions and immutable values. It doesn’t look bad so far, does it? If it all feels too easy for you, let’s see if you can correctly answer the following question.
Quick exercise
Assume that the expression Ref.of[IO , I nt](0) creates the concurrently accessible mutable reference to an Int value that is initially 0 . What, in your opinion, should be the type of this expression? | Answer: IO[Ref[IO, Int]]
|
## Using `Ref` values
Not only updating a concurrently accessible mutable reference to an immutable value is side-effectful. **Creating** such a value is side-effectful too! This fact is represented in the `Ref.of` function signature:
```
def of(a: A): IO[Ref[IO, A]]
```
`Ref.of` returns a description of a program, which, when executed, will return an immutable `Ref` value that represents a concurrently mutable reference. **Updating** this mutable reference is described as another `IO` value (returned by the `update` function we have just discussed).
A very similar story can be told when it comes to **getting** the value held by the concurrent reference. `Ref[IO, A]` has a `get` function that returns ... an `IO[A]` of course!
```
def get: IO[A]
```

We have dealt with so many side-effectful programs in the last two chapters that we can now repurpose the lightning symbol to represent the `IO` value that describes an unsafe program, which needs to be executed later in the codebase. Earlier, we marked only bare unsafe code this way.
Combining all of this knowledge allows us to create a simple program, which, while still single-threaded—we still don’t know how to create threads in FP—shows how the `Ref` API behaves in the wild. We are going to introduce multithreaded programs very soon, and we’ll take full advantage of `Ref` then. For now, the following example doesn’t really provide any benefit over using an `Int` directly; it’s just an API demonstration.
This example is not spectacular, but all these three functions and `Ref` will come in handy once we start using them in multiple threads. Note that all update operations are guaranteed to be executed safely (i.e., they will never overwrite any updates coming from other threads).
> | val example: IO[Int] = for { counter <- Ref.of[IO, Int](0)
_ <- counter.update(_ + 3)
result <- counter.get
} yield result
example.unsafeRunSync()
→ 3 |
We use all three functions: `Ref.of` , `update` and `get` . Remember that each of them returns an `IO` value, and that is why we can safely `flatMap` them all in a single for comprehension.
If you don’t use the book’s `sbt console` , `import cats.effect._` .
## Making it all concurrent
Step 2
**`IO` s with fibers**
We know how `Refs` work and how they embrace the compare-and-swap mechanism without making programmers think too much about all the possible execution orders in the concurrent environment—it’s much more declarative than the imperative solutions presented earlier. Starting a new thread is done in a similar spirit. You don’t have to create any `Thread` objects. **You just need to declaratively state which things should run in parallel** . In a sense, a concurrent application is just a bunch of small, sequential, side-effectful programs running in parallel. And if you think about it long enough, you’ll notice that we already have a value that describes a sequential, side-effectful program: an `IO` . Intuitively, we should have an option to execute a list of `IO` s using multiple threads, right? And we do! Let’s see this in action. Here’s a _sequential_ program .
> | val exampleSequential: IO[Int] = for { counter <- Ref.of[IO, Int](0)
_ <- List(counter.update(_ + 2),
counter.update(_ + 3),
counter.update(_ + 4)).sequence
result <- counter.get
} yield result
exampleSequential.unsafeRunSync()
→ 9 |
Remember that `update` returns an `IO` value, so we have a `List` of three `IO` values. As you remember, calling `sequence` on such a `List` returns a single `IO` value that, when executed, will execute all the `IO` values from the original `List` and return their results as a `List` .
The `sequence` function, which is defined on a `List` of `IO` values, executes them in a sequence, just like the for comprehension ( `flatMap` s) executes `IO` values sequentially. However, note that none of the three `IO` values—three different `Ref` updates—depends on each other, so they don’t need to be executed one by one (sequentially). On the other hand, the creation of the `counter Ref` value needs to happen before any `counter.update` programs because they all use (or depend on) the `counter` value. Hence, we still need to use `flatMap` in this case, but we can safely run the three `counter.update` programs in parallel. And it’s not hard at all—we can do so using the **`parSequence`** function.
THIS IS BIG!
In FP, a multi-threaded program can be modeled as an immutable list of sequential programs.
> | val exampleConcurrent: IO[Int] = for { counter <- Ref.of[IO, Int](0)
_ <- List(counter.update(_ + 2),
counter.update(_ + 3),
counter.update(_ + 4)).parSequence
result <- counter.get
} yield result
exampleConcurrent.unsafeRunSync()
→ 9 |
 `parSequence` has the same API: it takes a `List` of `IO` values and returns an `IO` value describing a program that, when executed, will execute all the IO programs and return their results in a `List` . However, unlike `sequence` , `parSequence` doesn’t run the `IO` s sequentially; it runs them in parallel, each in its own “thread"!
## `parSequence` in action
The programs we tried to run in parallel are very small, and therefore, we can’t really see any difference in the running time between `sequence` and `parSequence` . Let’s change that and introduce some latency to our `IO` programs. Let’s use `IO.sleep` that has the following signature:
```
def sleep(delay: FiniteDuration): IO[Unit]
```
This function returns an IO value that describes a program that, when executed, sleeps for a given time and returns. This is the purely functional equivalent of `Thread.sleep` . It doesn’t block any threads.
We say it’s asynchronous and non-blocking, meaning that it doesn’t block any threads while waiting. The threads can therefore be used by other pieces of functionality.
Again, when we use `flatMap` , we get a sequential program, so to have an `IO` value describing a program that first sleeps for one second and then updates the `Ref` value adding `3` , we can just write
```sql
IO.sleep(FiniteDuration(1, TimeUnit.SECONDS))
.flatMap(_ => counter.update(_ + 3))
```
A two-step for comprehension would work here as well.
We can use `sleep` to update our previous example and have three counter updates, but two of them executing after waiting for one second.

How long (in seconds) will both versions be running when executed? In most scenarios, the `sequence` -based program will run for at least two seconds because all three programs are running one by one. The `parSequence` -based version **will run for at least one second** . In this version the three programs described by the three `IO` values are executed in parallel, safely updating the concurrent mutable reference ( `counter` ). During its execution, the IO value created using `parSequence` waits for all three “threads” to finish their work before returning a value (a list of program results) or an error in case at least one `IO` failed. If everything goes well, we get `9` as a result— **no race conditions, no surprises** .
Handling errors in programs described by `IO` values works exactly the same as in sequential ones. We learned all the techniques previously.
We were able to create an `IO` value describing a concurrent program that always returns the value we expect. And since it’s a concurrent program described by a single `IO` value, we can use it in any place we used other `IO` values previously. It’s a seamless integration with all the other programs. But how does concurrent `IO` work internally?
Threads and fibers 
Notice that when we write “threads” (in quotes) we don’t really mean the threads you are accustomed to from imperative languages. Classically, a `Thread` object, which is an operating system’s native thread under the hood, incurs a large overhead—allocating and deallocating threads are heavyweight operations due to underlying operating system native calls. That’s why many modern applications use **thread pools** —preallocated sets of worker threads that execute submitted logic.
However, both solutions—manually creating OS-level threads and using thread pools—suffer from a more pressing issue. They are pretty low-level, and they require a lot of code to cover all the corner cases. When using these approaches, programmers need to write and maintain code, which is not usually related to an essential business concern. Creating and managing concurrent threads of execution should be a more straightforward endeavor. From the business logic perspective, we’d ideally want to just say “run this in parallel”—it should be as simple as that. Handling corner cases, thread pools, and scheduling things to run in parallel are not simple tasks, and more importantly, they shouldn’t clutter the logic of our application! Hence, there is a big trade-off between simplicity, correctness, and efficiency in writing concurrent programs.
Many modern programming languages and libraries, including Scala, use a more lightweight concept for threads: **fibers** (or _green threads_ ). This is an efficient concurrency mechanism, which is not connected directly with OS-level threading and, therefore, is much more usable, light, and worry-free. Conceptually, they are used for exactly the same thing: to run things in parallel.
Note that there is a difference between concurrency and parallelism. When you run two pieces of logic concurrently, it means that they may start and make progress in the same time period. Even a single CPU core can run them concurrently. When you run two pieces of logic in parallel, you need at least two cores to run them exactly at the same time, simultaneously—one alongside the other.
Fibers are sometimes called logical threads because they are just objects representing computations, while the real work is still done on real threads, which are now a more low-level concept. Many fibers can be executed on a single thread. We still use thread pools, but they are **completely separated from the application perspective** . You don’t need any thread pools to create an `IO` value. You need a thread pool only when you want to execute it. This idea improves maintainability and helps us focus on the logic—not accidental concerns.
We have already used `import cats.effect.unsafe.implicits.global` in chapter 9. That’s where thread pools are configured. You can always provide your own configuration.
Fibers have made their way into imperative languages, too. Java will introduce them as a part of Project Loom. They are called virtual threads there, but the underlying principles are very similar.
THIS IS BIG!
In functional programs we work with fibers instead of OS-level threads.
## Practicing concurrent `IO` s
It’s time we check your understanding of fibers and concurrent states. Let’s go back to a familiar example where we use an `IO` value:
```
def castTheDie(): IO[Int] ①
```
① `import ch10_CastingDieConcurrently.castTheDie`
Your task is to define the following IO values . Wait one second, then cast two dies concurrently, wait for both of them, and return their sum. Cast two dies concurrently, store each result in a concurrently accessible reference that holds a List , and, finally, return it as a result. Cast three dies concurrently, store each result in a concurrently accessible reference that holds a List , and, finally, return it as a result. Cast 100 dies concurrently, store the total number of 6 s in a concurrently accessible reference, and return its value as a result. Cast one hundred dies concurrently, waiting one second before each of them, and return their sum (without using a concurrent reference).
| Hint: You already know how to create lists of many programs. List.range will work here, but try using List.fill instead! Program #5, when executed, should run for a little bit more than one second. |
Answers
1 | for { _ <- IO.sleep(1.second)
result <- List(castTheDie(), castTheDie()).parSequence
} yield result.sum | After importing scala.concurrent.duration._ , you can easily transform any Int into FiniteDuration by using many built-in functions: second, seconds, milliseconds and more. |
2 | for {
storedCasts <- Ref.of[IO, List[Int]](List.empty)
singleCast = castTheDie()
.flatMap(result => storedCasts.update(_.appended(result)))
_ <- List(singleCast, singleCast).parSequence
casts <- storedCasts.get
} yield casts |
3 | for {
storedCasts <- Ref.of[IO, List[Int]](List.empty)
singleCast = castTheDie()
.flatMap(result => storedCasts.update(_.appended(result)))
_ <- List.fill(3)(singleCast).parSequence
casts <- storedCasts.get
} yield casts | You can use List.fill to create a list of many elements instead of using List.range(...).map(...) . |
4 | for {
storedCasts <- Ref.of[IO, Int](0)
singleCast = castTheDie().flatMap(result =>
if (result == 6) storedCasts.update(_ + 1) else IO.unit)
_ <- List.fill(100)(singleCast).parSequence
casts <- storedCasts.get
} yield casts | |
5 | List.fill(100)(IO.sleep(1.second).flatMap(_ => castTheDie())).parSequence.map(_.sum) | |
## Modeling concurrency
Let’s go back to our initial plan for creating the check-ins processor.

This diagram has been useful to model our thread-based world. However, knowing how fibers, `parSequence` , and `Ref` work, we can now model this application in a **functional way: using just values** and their relationships!
Modeling concurrently accessible references
We need two concurrent references: one for storing check-ins ( **`storedCheckIns`** ) and a second for storing the current ranking ( **`storedRanking`** ). This will ensure that getting the current ranking is a really fast operation because we will just read from memory instead of calculating the ranking on each read. This is a common optimization.
Modeling sequential and concurrent programs
We need at least two different sequential programs: **`checkInsProgram`** , which, when executed, will `drain` the input stream of check-ins, storing each of them safely in the `storedCheckIns` reference; and **`rankingProgram`** which, when executed, will infinitely read the current check-ins, calculate the ranking, and safely store it inside `storedRanking` . Both of them are IO values. We also know that the final solution needs to run both programs concurrently, and we can model that as another `IO` value.

You create fibers indirectly by transforming a list of `IO` values using `parSequence` . Hence, the whole program will just be an `IO` value that, when executed, will run “fibered" `IO` values concurrently.
## Coding using `Ref` s and fibers
Our previous version was a sequential program that looked like this:
Step 2
**`IO` s with fiber** .
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
checkIns
.scan(Map.empty[City, Int])((cityCheckIns, city) =>
cityCheckIns.updatedWith(city)(_.map(_ + 1).orElse(Some(1)))
)
.map(topCities)
.foreach(IO.println)
.compile.drain
}
```
We also wrote a better, batching version that used the `chunkN` stream combinator, but it had its disadvantages as well. The ranking wasn’t updating as often as we wanted.
We can, therefore, rewrite `processCheckIns` to a concurrent application. We will show how to implement it but then will leave a very tiny but important detail for you to implement, so pay attention because this is the place where all of what we’ve learned comes together.
❶ | Let’s delete the current implementation and start over. The for comprehension represents a sequential program. The first step will be to create both concurrent references: |
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
} yield ()
}
```
❷ | We need two programs: one for updating the ranking infinitely and the second to store the check-ins that appear in the incoming stream. Let’s start with the ranking one: |
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking) ①
} yield ()
}
def updateRanking(
storedCheckIns: Ref[IO, Map[City, Int]],
storedRanking: Ref[IO, List[CityStats]] ②
): IO[Unit] = ???
```
① We first define the `rankingProgram` IO value by calling the `updateRanking` function, which will be implemented later. We now focus on finishing the `processCheckIns` function. This is yet another example of the top-down approach to design, where we focus on the client side first. When we get the `processCheckIns` function right, we will be able to move "down" and fill all the unimplemented signatures.
② We will need this kind of function. It will need to read current checkins, calculate the ranking and store it in `storedRanking` . Then it will need to repeat the process again and again. It will need to happen concurrently with other functionalities.We will implement it soon.
❸ | The second program is the one that stores check-ins in the concurrently accessible reference. We already know how to transform a Stream value into an IO value. We need to run a program for each element in the stream. We’ll call it storeCheckIn and use it inside processCheckIns : |
```sql
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking)
checkInsProgram =
checkIns.evalMap(storeCheckIn(storedCheckIns)).compile.drain ①②
} yield ()
}
def storeCheckIn(
storedCheckIns: Ref[IO, Map[City, Int]]
)(city: City): IO[Unit] = {
storedCheckIns.update(_.updatedWith(city)(_ match { ③④
case None => Some(1)
case Some(checkIns) => Some(checkIns + 1)
}))
}
```
① This `evalMap` combinator is an alias for writing `checkIns.flatMap(checkIn => Stream.eval(storeCheckIn(checkIn)))` . It maps each city element with the provided function and evaluates it. This is useful when you want to run an side-efiectful program for each element in your stream. In our case, we need side efiects because we are updating concurrently accessible references.
② `compile.drain` transforms the stream into an `IO[Unit]` value.
③ `storedCheckIns` is a `Ref` value, which has the update function. Remember that the update function, in this case, takes a `Map[City, Int]` and returns a new `Map[City, Int]` . It needs to return a new Map that has an updated check-ins value for a given `city` . We could use the Map.updated function we learned previously, but using `updatedWith` is much more concise. It takes a function that takes an element which is an `Option` ( `None` meaning that there is no value under the given `city` key), and returns a new `Option` . Returning `None` means we want to remove the value, but we always return `Some` in our pattern matching expression: `Some(1)` when the value was not there before and `Some(checkIns + 1)` if it was.
④ This function has two parameter lists. It's curried to allow for more convenient usage in the processCheckIns function.
❹ | Finally, we need to run both programs concurrently. That means we need parSequence: |
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking)
checkInsProgram = checkIns.evalMap(storeCheckIn(storedCheckIns)).compile.drain
_ <- List(rankingProgram, checkInsProgram).parSequence
} yield ()
}
```
Note we only use a two fibers: `rankingProgram` and `checkInsProgram` . In reality we’d probably have many fibers processing batches of check-ins, which can be implemented very similarly to what we just showed by adding more `IO` values to the `List` . Nothing else would need to change because this implementation is already safe, despite being concurrent.
This function works, but there are still two unresolved issues with it:
- The **`updateRanking`** function needs an implementation.
- When we execute the **`IO`** value returned by **`processCheckIns`** , it will run without any feedback! We haven’t provided any way to output a current ranking for the users—not even a simple **`println`** .
## `IO` s that run infinitely
Let’s first implement the function that infinitely updates the ranking. We can do it using recursion, as we did in the previous chapter.
`topCities`
a function we implemented earlier that takes a `Map[City, Int]` and returns a `List[CityStats]` , which is a TOP3 ranking
> | def updateRanking( storedCheckIns: Ref[IO, Map[City, Int]],
storedRanking: Ref[IO, List[CityStats]]
): IO[Unit] = {
for {
newRanking <- storedCheckIns.get.map(topCities)
_ <- storedRanking.set(newRanking)
_ <- updateRanking(storedCheckIns, storedRanking)
} yield ()
} |
This will work fine. However, note that the `IO[Unit]` return type doesn’t convey a very important aspect of this function: it will never complete. Fortunately, there is a way to fix that. **Meet the `Nothing` type** .
> | def updateRanking( storedCheckIns: Ref[IO, Map[City, Int]],
storedRanking: Ref[IO, List[CityStats]]
): IO[Nothing] = { ①
for {
newRanking <- storedCheckIns.get.map(topCities)
_ <- storedRanking.set(newRanking)
result <- updateRanking(storedCheckIns, storedRanking)
} yield result ②
}① Nothing is a type that doesn’t have any values. You can’t create any values of type Nothing . However, by using recursion, we can still create a compiling function that returns IO[Nothing] . ② result has the Nothing type here. Note that it will never be any value, because it’s defined using an infinite recursion. |
We can also use the **`foreverM`** function to achieve the same result.
> | def updateRanking( storedCheckIns: Ref[IO, Map[City, Int]],
storedRanking: Ref[IO, List[CityStats]]
): IO[Nothing] = {
(for {
newRanking <- storedCheckIns.get.map(topCities)
_ <- storedRanking.set(newRanking)
} yield ()).foreverM ①
}① foreverM transforms a given IO[A] and returns an IO[Nothing] , which is a description of a program created by repeating the given IO indefinitely (so it won’t ever return, hence, Nothing ). We didn’t need to use it before because we had only one thread to work with, and executing such an IO value synchronously on a single thread will take “forever." (Note that for streams we use repeat to achieve a similar result.) |
> | def updateRanking( storedCheckIns: Ref[IO, Map[City, Int]],
storedRanking: Ref[IO, List[CityStats]]
): IO[Nothing] = { ①
storedCheckIns.get
.map(topCities) ②
.flatMap(storedRanking.set) ②
.foreverM
}① IO[Nothing] means that the program, when executed, will not return or will fail. The Nothing type is called a “bottom type" in other FP languages. ② The last alternative we want to show is for people who prefer using flatMap/map sequences instead of for comprehensions. Again, this may be good for some teams and not for others. |
## Coffee break: Concurrent thinking 
We now have a program that has some pieces that run concurrently. However, we still need one more thing: the implementation of the second requirement.
Requirements: City rankings
1. The program needs to process a stream of check-ins from people around the world (a **`Stream[IO, City]`** value will be provided).
2. The program should allow getting the current top three cities’ ranking (ranked by check-ins), while the check-ins are still being processed.
Our users need to be able to see the current version of the ranking. We will spend the rest of the chapter implementing the most convenient—asynchronous—way of doing so, but before we do that, let’s practice what we learned so far by writing a more basic version.
Here’s the current version of `processCheckIns` function:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking)
checkInsProgram = checkIns.evalMap(storeCheckIn(storedCheckIns))
.compile.drain
_ <- List(rankingProgram, checkInsProgram).parSequence
} yield ()
}
```
**Update this function to a version that** works exactly the same but additionally **prints the current ranking every one second** .

`outputProgram` needs to run concurrently with others. It should first wait one second, then read the current ranking, print it, and repeat the process, starting with waiting.
## Coffee break explained: Concurrent thinking 
There are many ways you could have approached this exercise. There are a few points that needed to be considered—no matter what your final solution looks like.
A correct solution should include a new `IO` value in the `List` we are calling the `parSequence` function on. That means that there is going to be another IO program running concurrently when the whole function is executed. Secondly, a correct solution should make sure that printing the ranking happens every one second and repeats indefinitely.
Here’s one possible version of the `processCheckIns` function that takes into consideration both aspects:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking)
checkInsProgram =
checkIns.evalMap(storeCheckIn(storedCheckIns)).compile.drain
outputProgram =
IO.sleep(1.second) ①
.flatMap(_ => storedRanking.get)
.flatMap(IO.println)
.foreverM
_ <- List(
rankingProgram,
checkInsProgram,
outputProgram).parSequence ②
} yield ()
}
```
① We need to create a new IO value that describes a program that first sleeps for one second, then gets a current value of the ranking, then prints it to the console, and finally repeats the process from the start forever.
② We then include this value in a `List` of `IO` s, which we then `parSequence` into an `IO` of `List` s, running all the programs concurrently on a thread pool provided later in the program, outside of the functional core.
This is just one possibility. We could refactor the whole `outputProgram` implementation to another function like we did with the `rankingProgram` . We could also use recursion instead of `foreverM` or use a for comprehension instead of `flatMap` s. All of these solutions would be valid. The important thing is that running the `IO` returned by this function should never finish, **printing** the ranking every second.
> | import cats.effect.unsafe.implicits.global processCheckIns(checkIns).unsafeRunSync() ①
→ console output: List(CityStats(City(Sydney),100002), ...)
... ① Remember that you need to provide a thread pool that will be used to run your fibers on. This is required when you want to call the unsafeRunSync . You don’t have to do it in the book’s sbt console . |
## The need for asynchronicity
We now have solutions for two major parts of the puzzle:
- The ability to process check-ins
- The ability to keep the ranking updated
We are almost there. There is still one problem, though. The access to the ranking is not the most user-friendly approach. Printing to the console may be a good idea for development when we debug and check if everything goes according to the plan, but it’s not a production-ready solution. We can do better.
Let’s talk briefly about the API we currently expose and why it’s no longer enough:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[Unit]
```
When you run a program like that, it spawns some threads that process all incoming check-ins and update the ranking. You expect that it won’t finish any time soon. And indeed, our current solution runs forever, printing the ranking every second. But the requirements say that we want to be able to access the current ranking at any given moment—no matter how many check-ins have already been processed—not every second, as we encoded in the current version.
Yes, the program we implemented is concurrent; it uses many fibers, but it doesn’t give its users any choice regarding the way rankings are “consumed.” We encoded the `outputProgram` inside the `processCheckIns` function, but it’s encapsulated, and the behavior is not customizable at all. Additionally, this function shouldn’t be responsible for both producing and consuming the data. We could invert the control by returning a `Stream` or by adding an additional parameter(s) to the `processCheckIns` function (e.g., `outputAction` , which takes a ranking and returns an `IO` value that describes a program that consumes a ranking). These would all be welcome adjustments, but we can do even better: completely isolate the processing of check-ins and generating the ranking by using the current ranking in whatever way someone needs. We need to start the threads **asynchronously** .
However, we’d probably need to expose the `1.second` as a parameter as well, so exposing everything as a parameter may not be a good solution, either.
Step 2 ✔ IO s with fiber .
We will start using multiple threads (and potentially multiple cores) by learning about fibers.We will also need to store the current state safely, in a FP manner. | Step 3 Concurrent IO s and asynchronous acces . In the last step we will show how to create a program that returns a handle to all running resources (including fibers and states) asynchronously in a user-friendly and readable manner. |
## Preparing for asynchronous access
Synchronous vs. asynchronous
Even though our current program is concurrent, we use it in a **synchronous** way. That is, we execute the program and must **wait for it to complete** . Only when we receive a result of our program can we proceed with executing the next ones. We say that the **caller thread blocks** while waiting for a result. If the program takes a long time to complete, the caller thread is blocked for a long time. In the case of `processCheckIns` , running the `IO` value is never going to finish, so we end up blocking the caller thread ( `main` in this case).
On the other hand, **asynchronous** communication happens when the caller thread initiates a program and doesn’t wait for it to finish but instead proceeds with the next ones. If it cares about the results provided by such a program, it will need to have a way to get them by providing a callback or using some kind of “handle” that has access to them. No matter which way is used, we say that the caller thread accesses the results asynchronously.
That all sounds good for our case, so we’d like to replace the current, synchronous solution with an asynchronous one.
Synchronous

Asynchronous


## Designing functional asynchronous programs
We need a function that returns a program, which, when executed, spawns all the threads, connects them together using concurrent references, and returns immediately, giving back a handle that allows us to access the current ranking any time.
Since we model everything as immutable values, we can also model such an asynchronous handle as an immutable value. We will call it `ProcessingCheckIns` :
There are some built-in solutions for a problem like that in FP libraries (e.g., the `Resource` type), and we will cover them in the last part of the book. For now, the important aspect to focus on here is the mindset. This example shows how immutable and purely functional thinking can be used to elegantly solve a very imperative-looking problem like the one in this chapter.
```
case class ProcessingCheckIns(
currentRanking: IO[List[CityStats]],
stop: IO[Unit]
)
```
This product type can now become part of the return type:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[ProcessingCheckIns]
```
Before we implement the new version, let’s see how a function with such an API could be use to allow asynchronous access:
```
for {
processing <- processCheckIns(checkIns)
ranking <- processing.currentRanking
_ <- IO.println(ranking)
_ <- IO.sleep(1.second)
... // more things here
newRanking <- processing.currentRanking
_ <- processing.stop
} yield newRanking
```
This `IO` value, when executed, runs processing and ranking fibers concurrently and returns immediately. Then, it prints the current ranking; sleeps for one second; does “more things"; and then gets an up-to-date version of the ranking, stops the processing, and yields a ranking.
This is an example of a program that our clients could write. They first need to call the `processCheckIns` function, which spawns all the fibers and immediately returns the `ProcessingCheckIns` value that holds two `IO` values: one that returns the current ranking and one that stops all the fibers. That means that the client is now responsible for executing both of them at their convenience. They could get the newest ranking every second, every minute, or 100 times an hour. It doesn’t matter from the perspective of the `processCheckIns` developer. By using asynchronous communication, we are able to decouple producing ranking from its consumption. Only one question remains: how difficult is implementing such a solution?
## Managing fibers manually
Fortunately, the `IO` type has a function that allows us to execute a given IO value in a fiber and returns a handle to this fiber without waiting for it to finish.
```
def start[A]: IO[FiberIO[A]] ①
```
① The function `start` is defined for `IO` values.
Don’t be misled by the imperative name of the `start` function. The signature tells a declarative story: this function returns a description of a program, which, when executed, will start a new fiber and immediately return a handle to this thread represented by an immutable `FiberIO[A]` value. You are able to do several things with this handle, but the most important one is the `cancel` function.
```
def cancel: IO[Unit] ①
```
① The `cancel` function is defined for `FiberIO[A]` values (i.e., handles returned by the program described by `IO.start` ).
The handle has a `cancel` function that returns an `IO[Unit]` —a program, which, when executed, cancels the underlying fiber.
Quick exercise 
Let’s see if we’ve got this right. What does the following program do? How long will it run?
```
for {
fiber <- IO.sleep(300.millis)
.flatMap(_ => IO.println("hello")).foreverM.start
_ <- IO.sleep(1.second)
_ <- fiber.cancel
_ <- IO.sleep(1.second)
} yield ()
```
Starting fibers manually considered low-level
Note that using the `parSequence` function we discussed earlier (and other functions with similar semantics) is considered a better choice for creating concurrent `IO` s than functions like `start` and `cancel` . The main difference is that when you start a fiber manually (using `start` ), you become completely responsible for making sure it stops and nothing leaks, while `parSequence` (and other declarative functions) take care of those things for you, even when something fails.
You should use `parSequence` or its “siblings” (see the book’s companion source code for more information) whenever you can and treat `IO.start` , `FiberIO.cancel` and other less declarative options as a last resort. Remember to double-check whether they really finish when you no longer need them (even when something fails).
Answer
The IO value above starts a fiber which prints “hello" every 300 milliseconds infinitely and returns a handle to it. After one second the fiber is canceled, which means that, most likely, the program will print “hello" three times and should take around two seconds.
## Coding functional asynchronous programs
Let’s use the recently met `start` and `cancel` functions to model the final version of the `processCheckIns` that has the following signature:
```
def processCheckIns(checkIns: Stream[IO, City]): IO[ProcessingCheckIns]
```
This API means that the program returns a handle (immutable value of `ProcessingCheckIns` ) that allows the user to get the current ranking any number of times at any given moment. No strings attached. It also allows the user to explicitly stop all the underlying fibers once they don’t need the ranking anymore.
```
case class ProcessingCheckIns(
currentRanking: IO[List[CityStats]],
stop: IO[Unit]
)
```
The changes we need to apply to the existing `processCheckIns` function are not extensive. We need to run yet another fiber that will be the “parent” of the two fibers responsible for storing check-ins and updating the ranking. No thread will be wasted in the process because fibers don’t use any threads when they are not doing anything.
This parent fiber will be “waiting" for both child fibers to “finish." They will probably not finish (as designed), but it’s not important here. Having access to the parent fiber means we only need to `cancel` this one. We don’t have to `cancel` its “children" individually.
```
def processCheckIns(
checkIns: Stream[IO, City]
): IO[ProcessingCheckIns] = {
for {
storedCheckIns <- Ref.of[IO, Map[City, Int]](Map.empty)
storedRanking <- Ref.of[IO, List[CityStats]](List.empty)
rankingProgram = updateRanking(storedCheckIns, storedRanking)
checkInsProgram = checkIns.evalMap(storeCheckIn(storedCheckIns))
.compile.drain
fiber <- List(rankingProgram,
checkInsProgram).parSequence.start ①
} yield ProcessingCheckIns(storedRanking.get, fiber.cancel) ②
}
```
① Note that we no longer need any `outputProgram` because now the client is responsible for reading and using the ranking.
② We can return the `storedRanking.get IO` value as a way to quickly read the current ranking and `fiber.cancel` as a way to cancel the fiber that waits for both `parSequence` d programs— `rankingProgram` and `checkInsProgram` —to finish.
That’s a wrap! The solution above is all we need to implement the requirements in a concise, safe, and readable manner. The best thing is that we used only pure functions and immutable values to do that!
Step 3 ✔
**Concurrent `IO` s and asynchronous acces** .
In the last step we will show how to create a program that returns a handle to all running resources (including fibers and states) asynchronously in a user-friendly and readable manner.
## Summary
We showed some basic functional concurrent concepts that are available in many FP languages. The main objective was to show you how all the ideas, concepts, and mental models we learned from sequential programs are still applicable here. Hopefully, it gives you a good intuition about how more advanced types and mechanism can be used to solve even more complicated concurrency problems. The following sections cover what we’ve learned this chapter.
CODE: `CH10_*`
Explore this chapter’s source code by looking at `ch10_*` files in the book’s repository.
Declaratively design concurrent program flows
We used `parSequence` to transform a `List` of `IO` values into an `IO` of a `List` . This function is similar to `sequence` , but it runs the programs described by `IO` values **concurrently** —not sequentially. We compared this approach to some more traditional and imperative concurrency models like monitors, locks, actors, and thread-safe data structures.
There are other functions that run `IO` s concurrently. For example, have a look at `parTraverse` .
Use lightweight virtual threads (fibers)
`parSequence` and other functions are taking advantage of the fibers’ mechanism that is also available in many other languages. A fiber is a higher-level concept than a `Thread` object. Unlike `Thread` s, fibers are not mapped to operating system threads. That means they are very lightweight, and you can create many of them.
Safely store and access data from different threads
The `Ref[IO, A]` value represents a mutable reference that can be accessed and changed by many threads at once. It uses the well-known compare-and-swap operation, which is also available in Java’s `AtomicReference` (and similar types). It provides a very straightforward way to update this reference. Programmers need to provide a pure function that takes a current value and returns the new one.
If you want to use more concurrent goodies in Scala, go to the cats-effect library documentation, and dive right in!
Process stream of events asynchronously
Finally, we implemented an asynchronous communication model by using the low-level `IO.start` and `FiberIO.cancel` functions.
As a final note, remember that concurrency is hard! Whenever possible, err on the side of sequential execution. Use concurrency and multiple threads only when needed. When you mostly stick to using `parSequence` , you are covered because it’s a concept that gives you a lot without any big trade-offs. We will discuss some additional concurrency concepts in chapter 12, but the main underlying idea will stay the same.