ConcurrentMap.putIfAbsent(Object, Supplier)? (original) (raw)
Philippe Marschall kustos at gmx.net
Sun May 26 11:22:37 UTC 2013
- Previous message: AutoCloseable XMLStreamReader and XMLStreamWriter?
- Next message: ConcurrentMap.putIfAbsent(Object, Supplier)?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 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
- Previous message: AutoCloseable XMLStreamReader and XMLStreamWriter?
- Next message: ConcurrentMap.putIfAbsent(Object, Supplier)?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]