ConcurrentMap.putIfAbsent(Object, Supplier)?
Philippe Marschall
kustos at gmx.net
Sun May 26 11:22:37 UTC 2013
Hi
I often find myself writing code like this:
ConcurrentMap map = ...;
Object value = map.get(key);
if (value == null) {
Object newValue = expensiveComputation();
Object previous = map.putIfAbsent(key, newValue);
if (previous != null) {
value = previous;
} else {
value = newValue;
}
}
return value;
This is quite error prone and tedious. If we had a method:
V putIfAbsent(K key, Supplier<V> Supplier)
it could be replaced with
return map.get(key, () -> expensiveComputation());
It could even be implemented with a default method assuming null values
aren't allowed which is the same as for the new #getOrDefault default
method.
Cheers
Philippe
More information about the core-libs-dev
mailing list