Using Cats Effect's MapRef
(all code samples can be run using scala-cli)
If you use Cats Effect (CE) it is likely you have found that you need a Map
instance that has to be fiber-safe as several fibers can access it concurrently. MapRef is a type offered by CE std package that accommodates such need. This post shows how to instantiate and use it in a CE application.
Instantiate your MapRef
, put and get data
Below you can find a simple example of how to instantiate and work with a MapRef[IO, Int, String]
, that is, a MapRef
that 'works' in IO
, and that contains a map with keys of type Int
and values of type String
:
Concurrency
Now, let's show off a bit the concurrent capabilities of MapRef
, this time by first inserting 20 elements and then getting them back again concurrently:
Note also that get
returns the value wrapped in a Ref
instance, so you can modify it in a safe manner and changes will be visible to other fibers accessing the same value, see Ref documentation.
Full control over the wrapped Map
Sometimes you need a bit more control over the wrapped map that the one given by the MapRef API. To do so you can create an instance of Java's ConcurrentHashMap
and then wrap it in a MapRef
instance, below you can find an example of how to do so, see how this code sample uses the ConcurrentHashMap
to retrieve the full list of keys:
Subscribe to my newsletter
Read articles from Luis Rodero-Merino directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Luis Rodero-Merino
Luis Rodero-Merino
Dev interested in functional programming solutions for Scala.