Skip to content

Instantly share code, notes, and snippets.

@viktorklang
Last active December 11, 2015 23:38
Show Gist options
  • Save viktorklang/4678041 to your computer and use it in GitHub Desktop.
Save viktorklang/4678041 to your computer and use it in GitHub Desktop.
Nonblocking cache
/*©2013 Viktor Klang*/
package akka.util
import java.util.concurrent.atomic.AtomicReference
import scala.concurrent.{ Future, ExecutionContext }
import scala.annotation.tailrec
class Cache[K, V](__ec: ExecutionContext, throughput: Int) extends AtomicReference[Map[K, V]] {
implicit val executor = SerializedSuspendableExecutionContext(throughput)(__ec)
@tailrec final def update(f: Map[K, V] ⇒ Map[K, V]): Map[K, V] = {
val v = get
val nv = f(v)
if ((v eq get) && compareAndSet(v, nv)) nv else update(f)
}
def alter(f: Map[K, V] ⇒ Map[K, V]): Future[Map[K, V]] = Future(update(f))
}
val c = new Cache[Foo, Bar](ExecutionContext.Implicits.global, 16)
/* Usage readers */
c.get.get("value")
/* Usage writers */
c.alter(_.updated(key, calculateValue))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment