Last active
December 11, 2015 23:38
-
-
Save viktorklang/4678041 to your computer and use it in GitHub Desktop.
Nonblocking cache
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
/*©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