From dba77034209f7f08e5b0f894d1973686f688c2d0 Mon Sep 17 00:00:00 2001 From: Christopher Vogt Date: Sat, 12 Mar 2016 00:02:22 -0500 Subject: A draft implementation that runs builds concurrently (probably buggy right now). Is CBT "reactive" now ;)? --- stage1/KeyLockedLazyCache.scala | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 stage1/KeyLockedLazyCache.scala (limited to 'stage1/KeyLockedLazyCache.scala') diff --git a/stage1/KeyLockedLazyCache.scala b/stage1/KeyLockedLazyCache.scala new file mode 100644 index 0000000..c8b37ea --- /dev/null +++ b/stage1/KeyLockedLazyCache.scala @@ -0,0 +1,33 @@ +/* +package cbt +import java.util.concurrent.ConcurrentHashMap +import scala.concurrent.Future + +/** +A cache that lazily computes values if needed during lookup. +Locking occurs on the key, so separate keys can be looked up +simultaneously without a deadlock. +*/ +final private[cbt] class KeyLockedLazyCache[Key <: AnyRef,Value]{ + private val keys = new ConcurrentHashMap[Key,LockableKey]() + private val builds = new ConcurrentHashMap[LockableKey,Value]() + + private class LockableKey + def get( key: Key, value: => Value ): Value = { + val keyObject = keys.synchronized{ + if( ! (keys containsKey key) ){ + keys.put( key, new LockableKey ) + } + keys get key + } + // synchronizing on key only, so asking for a particular key does + // not block the whole cache, but just that cache entry + key.synchronized{ + if( ! (builds containsKey keyObject) ){ + builds.put( keyObject, value ) + } + builds get keyObject + } + } +} +*/ -- cgit v1.2.3