Created
January 5, 2023 14:21
-
-
Save darkfrog26/e7d8b8a15ac7b380cc903f882a4e0f60 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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