Skip to content

Instantly share code, notes, and snippets.

@jedws
Created December 10, 2014 05:18
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 jedws/d2c42352375399095eae to your computer and use it in GitHub Desktop.
Save jedws/d2c42352375399095eae to your computer and use it in GitHub Desktop.
A memoizer that memoizes partial thunks, and caches values only if found (unsafe)
import kadai.concurrent.Atomic
class Memoize[A](thunk: => Option[A]) {
val atom: Atomic[Ref] = Atomic(Empty)
def get: A =
atom.get match {
case Value(a) => a
case exec @ Executing() => exec.await match {
case Some(a) => if (atom.get == exec && atom.compareAndSet(exec, Value(a))) a else get
case None => get
}
case Empty => atom.compareAndSet(Empty, Executing()); get
}
sealed trait Ref
case object Empty extends Ref
case class Executing() extends Ref {
lazy val await: Option[A] = thunk
}
case class Value(a: A) extends Ref
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment