Let's consider the following following code:
ConcurrentHashMap<String, Set<String>> map = new ConcurrentHashMap<>();
// Add element: {mapKey, setValue}
map.computeIfAbsent(mapKey, new Function<String, Set<String>>() {
@Override
public Set<String> apply(String mapK) {
return ConcurrentHashMap.newKeySet();
}
}).add(setValue);
// Remove element: {mapKey, setValue}
Set<String> updatedSet = map.computeIfPresent(mapKey, new BiFunction<String, Set<String>, Set<String>>() {
@Override
public Set<String> apply(String mapK, Set<String> old) {
old.remove(setValue);
return old;
}
});
// I need remove mapKey, but I cannod do this like this, because of race condition bug
if (updatedSet.isEmpty()) {
map.remove(mapKey);
}
So, what we can see:
- We have
ConcurrentHashMap<String, Set<String>>
map, wherekey
of map isString
, andvalue
isConcurrentHashSet
. - I need to remove
set
, which is value ofmap
, whenset
isempty
. - I cannot implement naive removing of
set
, because of race condition bug.
Is there any brilliant solution of my problem?