Given a ConcurrentHashMap<String, String>
contains following entries:
this.map = new ConcurrentHashMap<>();
this.map.put("user", "user description");
this.map.put("session", "session description");
this.map.put("test", "test description");
The map is accessed by multiple threads.
How to remove all keys, except session
in an atomic way?
Will this code work as I expect, without race conditions? Is forEach
method atomic? Is there any other way to achieve this atomically?
map.forEach((key, value) -> {
if (!key.equals("session")) {
map.remove(key);
}
});