dictionary - Implement java map accessed by multiple threads that is only updated once for each key -
i need create map accessed multiple threads , ever has 1 (not null) value inserted in it.
to clarify i'm trying :
object getvalue(key) { if(map.get(key) != null) return map.get(key) else { object obj = new object(); map.put(key, obj); return obj; } }
the easiest way make getvalue method synchronised, want make method efficient possible, requirement put 'else' part in synchronised block , locked somehow on 'key' value. best way implement this?
i suspect want computeifabsent method.
// support map allows concurrent access. concurrentmap<key,value> map = .... value oneperkey = map.computeifabsent(key, value::new);
or
value oneperkey = map.computeifabsent(key, key -> new value());
from javadoc computeifabsent
the default implementation equivalent following steps map, returning current value or null if absent:
if (map.get(key) == null) { v newvalue = mappingfunction.apply(key); if (newvalue != null) return map.putifabsent(key, newvalue); }
the default implementation may retry these steps when multiple threads attempt updates including potentially calling mapping function multiple times.
Comments
Post a Comment