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:
Collections.synchronizedMapwrapper method to create a synchronizable object. After that, directly use
synchronizedon the Map object itself. All modifications to the HashMap must be done using the synchronized object, not the original HashMap object.