Is iterating ConcurrentHashMap values thread safe?
Yes, iterating a ConcurrentHashMap's values is thread-safe. The iterator doesn't throw a ConcurrentModificationException and mirrors the map's frame when it was born.
Watch out, though! Any transformations to the map after our iterator's creation will be as visible as a White Walker in the Snowstorm!
Iterations and modifications
In this parallel universe where multiple threads love to modify your map while you're iterating it, just remember, ConcurrentHashMap supports ace concurrency of retrievals and anticipated concurrency for changes.
The Code you need:
- Stick to
iterator.remove()
when it's time to safely remove elements during the iteration – this will stop Ghost from digging up any bones. - Updates directly on
ConcurrentHashMap
while iterating over its children (entrySet()
,keySet()
, orvalues()
) is as safe as living beyond the Wall. (Well, at least before the White Walkers attacked.) - When modifying your map using an iterator, don’t forget to assign distinct iterators for each thread.
- Channel your best Maester and use your own
ExecutorService
to deal with the stubbornly concurrent tasks.
Complex synchronization
Beyond the Wall, ConcurrentHashMap makes external synchronization look like a summer's day, but in scenarios where your task is as complex as storing Wildfire, you will need extra synchronization.
The Quills and Parchments:
- While iterating and checking conditions: Keep your critical sections safer than the Citadel with
synchronized
orReentrantLock
. - For atomic operations, make use of
computeIfAbsent
or otherConcurrentHashMap
atomic methods.
Eye on the Compound Actions
For those Dragons' tasks
like checking-then-acting scenarios or compute and add, you might need extra handshakes between threads especially when you need to deal with atomicity.
Ways to tame your Dragon:
- Use the atomic methods like
compute
,merge
orcomputeIfAbsent
for your Dragon tasks. - Bundle your custom compound actions in a synchronized block with the map standing as the lock.
Was this article helpful?