Skip to content

Commit

Permalink
Merge pull request #402 from brharrington/dynamic-contention
Browse files Browse the repository at this point in the history
reduce thread contention for expiring cache
  • Loading branch information
dmuino committed Nov 30, 2016
2 parents 2e3618a + 82fa710 commit becbfb0
Showing 1 changed file with 20 additions and 1 deletion.
Expand Up @@ -125,11 +125,30 @@ private Function<K, Entry<V>> toEntry(final Function<K, V> underlying) {
return key -> new Entry<>(underlying.apply(key), 0L, clock);
}

/**
* This method should be used instead of the
* {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} call to minimize
* thread contention. This method does not require locking for the common case
* where the key exists, but potentially performs additional computation when
* absent.
*/
private Entry<V> computeIfAbsent(K key) {
Entry<V> v = map.get(key);
if (v == null) {
Entry<V> tmp = entryGetter.apply(key);
v = map.putIfAbsent(key, tmp);
if (v == null) {
v = tmp;
}
}
return v;
}

/**
* Get the (possibly cached) value for a given key.
*/
public V get(final K key) {
Entry<V> entry = map.computeIfAbsent(key, entryGetter);
Entry<V> entry = computeIfAbsent(key);
return entry.getValue();
}

Expand Down

0 comments on commit becbfb0

Please sign in to comment.