Java Interview Question

Use this intermediate question and answer to prepare for your next Java interview.

What happens when one thread modifies a HashMap while another thread is iterating the same map? What is the correct way to do this?

A HashMap is not a synchronized Map, meaning that it is not thread-safe. If a HashMap is modified by a thread while another thread is iterating it, a ConcurrentModificationException will be thrown.

There are two possible ways to do this correctly:

  1. Synchronize the HashMap manually by using an object encapsulating the HashMap.
  2. Using the Collections.synchronizedMap wrapper method to create a synchronizable object. After that, directly use synchronized on the Map object itself. All modifications to the HashMap must be done using the synchronized object, not the original HashMap object.

Looking for developers?