Anyone have a good way of iterating through a `ConcurrentHashMap` and removing items at the same tim...
b
Anyone have a good way of iterating through a
ConcurrentHashMap
and removing items at the same time?
s
The basic pattern is this:
Copy code
val iterator = map.entries.iterator()
while (iterator.hasNext()) {
    iterator.next()
    iterator.remove()
}
I think concurrent hash maps support removal via the iterator, though not all collections do
👍 1
c
yea. the specifics will depend on the atomicity needed - should the whole operation (iteration + removals) be atomic, or can some level of staleness be tolerated?
e
you can usually use retainAll/removeAll (with a predicate) instead of working with the iterator directly
👌 1