I've read question ConcurrentHashMap: avoid extra object creation with “putIfAbsent”. For ConcurrentHashMap<String, List<String>>
, multiple threads will get-set the same list. Before values.add(value);
get executed, entry may be removed and new member fail to be added. How to add new member in ConcurrentHashMap<String, List<String>>
without synchronized
or lock
?
private ConcurrentHashMap<String, List<String>> entries =
new ConcurrentHashMap<String, List<String>>();
public void record(String key, String value) {
List<String> values = entries.get(key);
if (values == null) {
values = Collections.synchronizedList(new ArrayList<String>());
List<String> values2 = entries.putIfAbsent(key, values);
if (values2 != null)
values = values2;
}
values.add(value); // entry may be removed here, and this member will lose.
}