Reputation: 11
How can I safely put elements in
ConcurrentMap <String, Set<Integer>> cmap = new ConcurrentMap<String, Set<Integer>>();
I operate on my concurrent map as follows:
Set<Integer>
Integer
to this key's
Set<Integer>
value.Upvotes: 1
Views: 357
Reputation: 6075
ConcurrentMap has a method to initialize the map value if missing. I assume also the set inside should be thread safe:
Set<Integer> set = cmap.computeIfAbsent(key,(k)-> Collections.newSetFromMap(new ConcurrentHashMap<>()));
set.add(value);
Before lambda:
Set<Integer> set = cmap.get(key);
if (set == null) {
set = Collections.newSetFromMap(new ConcurrentHashMap<>());
Set<Integer> prev = cmap.putIfAbsent(key, set);
if (prev != null) {
set = prev;
}
}
set.add(value);
Upvotes: 3
Reputation: 1704
In concurrent environment you probably should use concurrent map and concurrent set. For example ConcurrentHashMap
, and Collections.newSetFromMap(new ConcurrentHashMap<>())
. The ConcurrentHashMap.putIfAbsent()
method prevent race condition of if(!containsKey) put
mechanic.
So the code will looks like
public void add(String s, Integer i) {
cmap.putIfAbsent(s, Collections.newSetFromMap(new ConcurrentHashMap<>()));
Set<Integer> set = cmap.get(s);
set.add(i);
}
Upvotes: 0