Last active
March 10, 2024 12:45
-
-
Save lrodero/a1488dcf6eb5bf056c6c1d7aa8b5879b to your computer and use it in GitHub Desktop.
Using cats-effect's MapRef, full control
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 | |
import java.util.concurrent.{ConcurrentHashMap => JConcurrentHashMap} | |
object FullControlMapRef extends IOApp.Simple: | |
val fullControlSample = | |
def getKeys(jchm: JConcurrentHashMap[Int, String]): IO[List[Int]] = | |
import scala.jdk.CollectionConverters.* | |
IO(jchm.keys()).map(_.asScala.toList) | |
def printKeys(jchm: JConcurrentHashMap[Int, String]): IO[Unit] = | |
getKeys(jchm).map(_.mkString("keys: [", ", ", "]")) >>= IO.println | |
for | |
jchm <- IO(JConcurrentHashMap[Int, String]()) | |
mr = MapRef.fromConcurrentHashMap[IO, Int, String](jchm) | |
_ <- (1 to 20).map(k => mr.setKeyValue(k, k.toString)).toList.parSequence // Set values concurrently | |
_ <- printKeys(jchm) // Will print a list with the 20 keys | |
_ <- (1 to 20).map(k => mr.unsetKey(k)).toList.parSequence // Remove values concurrently | |
_ <- printKeys(jchm) // Will print an empty list | |
yield () | |
override val run = fullControlSample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment