ConcurrentMap.putIfAbsent(Object, Supplier)?
Peter Levart
peter.levart at gmail.com
Sun May 26 11:25:34 UTC 2013
Hi Philippe,
I think you are looking for Map.computeIfAbsent(K, Supplier) which was
added to Map interface recently.
Regards, Peter
On 05/26/2013 01:22 PM, Philippe Marschall wrote:
> 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