Last active
March 10, 2024 12:44
-
-
Save lrodero/f46906b7d9bde281117e37383b9ddc9b to your computer and use it in GitHub Desktop.
Using cats-effect's MapRef, concurrent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using scala 3.3 | |
//> using dep org.typelevel::cats-effect:3.5.4 | |
import cats.syntax.all.* | |
import cats.effect.{IO, IOApp} | |
import cats.effect.std.MapRef | |
object ConcurrencyMapRef extends IOApp.Simple: | |
private val concurrencySample = | |
for | |
mr <- MapRef.ofSingleImmutableMap[IO, Int, String]() | |
_ <- (1 to 20).map{ k => | |
mr.setKeyValue(k, k.toString) | |
}.toList.parSequence // Will run 20 puts in parallel | |
_ <- (1 to 20).map { k => | |
mr(k).get.flatMap: | |
case None => IO.raiseError(new NoSuchElementException(s"Not found value for key $k, this is actually impossible")) | |
case Some(v) => IO.println(s"Found value $v for key $k") | |
}.toList.parSequence // Will run 20 gets in parallel | |
yield () | |
override val run = concurrencySample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment