I am aggregating multiple values for keys in a multi-threaded environment. The keys are not known in advance. I thought I would do something like this:
class
In the end, I implemented a slight modification of @Bohemian's answer. His proposed solution overwrites the values
variable with the putIfAbsent
call, which creates the same problem I had before. The code that seems to work looks like this:
public void record(String key, String value) {
List values = entries.get(key);
if (values == null) {
values = Collections.synchronizedList(new ArrayList());
List values2 = entries.putIfAbsent(key, values);
if (values2 != null)
values = values2;
}
values.add(value);
}
It's not as elegant as I'd like, but it's better than the original that creates a new ArrayList
instance at every call.