Skip to content

Instantly share code, notes, and snippets.

@lrodero
Last active March 10, 2024 12:45
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/a1488dcf6eb5bf056c6c1d7aa8b5879b to your computer and use it in GitHub Desktop.
Save lrodero/a1488dcf6eb5bf056c6c1d7aa8b5879b to your computer and use it in GitHub Desktop.
Using cats-effect's MapRef, full control
//> 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