Created
December 10, 2014 05:18
-
-
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)
This file contains 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 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