Explain Codes LogoExplain Codes Logo

Is iterating ConcurrentHashMap values thread safe?

java
concurrent-programming
thread-safety
collections
Alex KataevbyAlex Kataev·Feb 24, 2025
TLDR

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.

// Meet our newborn <String, Integer> type ConcurrentHashMap ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // Populating the map with some "age" data - because why not? map.put("Jon Snow", 25); map.put("Samwell Tarly", 23); // Iterating over the values...as safe as walking beyond the wall with a dragonglass for (Integer age : map.values()) { // Just me talking to myself System.out.println("Another year survived in the Game of Thrones: " + age); }

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(), or values()) 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 or ReentrantLock.
  • For atomic operations, make use of computeIfAbsent or other ConcurrentHashMap 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 or computeIfAbsent for your Dragon tasks.
  • Bundle your custom compound actions in a synchronized block with the map standing as the lock.