Skip to content

Instantly share code, notes, and snippets.

@invkrh
Last active November 2, 2015 22:36
Show Gist options
  • Save invkrh/06684b4e7be48827e4c7 to your computer and use it in GitHub Desktop.
Save invkrh/06684b4e7be48827e4c7 to your computer and use it in GitHub Desktop.
Scala Type Parameter
import java.util.Map;
public interface Cache<K, V> {
V get(K k);
void put(K key, V v);
Map<K, V> asMap();
}
abstract class CacheImpl[K, V >: Null](value: V) extends Cache[K, V] {
val flag = true
override def get(key: K): V = if (flag) value else null
}
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import scala.collection.JavaConversions._
trait BatchLoadingCache[K, V] {
protected val underlyingCache: Cache[K, V]
protected def load(key: K): V
def get(key: K): V = {
var v = underlyingCache.get(key)
if (null == v) {
v = load(key)
underlyingCache.put(key, v)
}
v
}
}
trait AbstractSimpleCacheScala[K, V] extends BatchLoadingCache[K, V] {
self =>
protected val underlyingCache: InternalCache = new InternalCache()
class InternalCache extends Cache[K, V] {
private val cache = new ConcurrentHashMap[K, V]()
override def asMap(): ConcurrentMap[K, V] = cache
override def get(k: K): V = cache.get(k)
override def put(key: K, v: V): Unit = cache.put(key, v)
}
}
class TestCache extends AbstractSimpleCacheScala[Long, String] {
def getAll: Map[Long, String] = {
underlyingCache.asMap().toMap
}
override protected def load(key: Long): String = underlyingCache.get(key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment