我正在创建一个具有以下特征的memoization缓存:
什么会有一个优越的性能,或在什么条件下一个解决方案优于另一个解决方案?
ThreadLocal HashMap:
class MyCache {
private static class LocalMyCache {
final Map<K,V> map = new HashMap<K,V>();
V get(K key) {
V val = map.get(key);
if (val == null) {
val = computeVal(key);
map.put(key, val);
}
return val;
}
}
private final ThreadLocal<LocalMyCache> localCaches = new ThreadLocal<LocalMyCache>() {
protected LocalMyCache initialValue() {
return new LocalMyCache();
}
};
public V get(K key) {
return localCaches.get().get(key);
}
}
Run Code Online (Sandbox Code Playgroud)
ConcurrentHashMap的: …