Skip to content

Instantly share code, notes, and snippets.

@lrodero
Last active March 10, 2024 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lrodero/f46906b7d9bde281117e37383b9ddc9b to your computer and use it in GitHub Desktop.
Save lrodero/f46906b7d9bde281117e37383b9ddc9b to your computer and use it in GitHub Desktop.
Using cats-effect's MapRef, concurrent
//> 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