Skip to content

Instantly share code, notes, and snippets.

@darkfrog26
Created January 5, 2023 14:21
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 darkfrog26/e7d8b8a15ac7b380cc903f882a4e0f60 to your computer and use it in GitHub Desktop.
Save darkfrog26/e7d8b8a15ac7b380cc903f882a4e0f60 to your computer and use it in GitHub Desktop.
import cats.effect.{Deferred, IO}
import java.util.concurrent.ConcurrentHashMap
trait WorkCache[Key, Result] {
private val map = new ConcurrentHashMap[Key, Deferred[IO, Result]]
protected def persisted(key: Key): IO[Option[Result]]
protected def work(key: Key): IO[Result]
def apply(key: Key): IO[Result] = IO(Option(map.get(key))).flatMap {
case Some(d) => d.get
case None => persisted(key).flatMap {
case Some(result) => IO.pure(result)
case None => Deferred[IO, Result].flatMap { d =>
map.put(key, d)
work(key).flatMap { result =>
d.complete(result).map { _ =>
map.remove(key)
result
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment