Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

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);
}
Model answerPreview

Root cause

  • HashMap is not thread-safe; concurrent put while iterating values() triggers CME.
  • The metrics loop mutates structural state…