Java · Medium · Pro
Debug: intermittent ConcurrentModificationException under load
JavaCollectionsConcurrencySenior
A cache map throws ConcurrentModificationException when traffic spikes.
Java
Map<String, User> cache = new HashMap<>();
public User getUser(String id) {
if (!cache.containsKey(id)) {
cache.put(id, userRepository.findById(id));
}
for (User u : cache.values()) { // warm metrics
metrics.record(u.getId());
}
return cache.get(id);
}Root cause
HashMapis not thread-safe; concurrentputwhile iteratingvalues()triggers CME.- The metrics loop mutates structural state…