Skip to content

Instantly share code, notes, and snippets.

@jilen
Created February 15, 2019 10:35
Show Gist options
  • Save jilen/317aae496d73f06c33ceaab7582b679b to your computer and use it in GitHub Desktop.
Save jilen/317aae496d73f06c33ceaab7582b679b to your computer and use it in GitHub Desktop.
A thread safe map using cats-effect
import cats._
import cats.effect._
import cats.effect.concurrent._
import cats.syntax.all._
class SafeMap[F[_], K, V](ref: Ref[F, Map[K, V]])(implicit F: Functor[F]) {
def putIfAbsent(k: K, v: V): F[Option[V]] = ref.modify { m =>
m.get(k) match {
case None =>
(m + (k -> v), None)
case Some(v) =>
(m, Some(v))
}
}
def remove(k: K, old: V): F[Boolean] = ref.modify { m =>
m.get(k) match {
case Some(v) if v == old =>
(m - k, true)
case _ => (m, false)
}
}
def get(k: K): F[Option[V]] = ref.get.map(_.get(k))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment