I have the following code:
static final Map<String, String> map = Collections.synchronizedMap(new HashMap());
public static void main(String[] args) throws InterruptedException {
map.put("1", "1");
map.put("2", "2");
new Thread(new Runnable() {
@Override
public void run() {
for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
System.out.println("after iterator");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Thread.sleep(50);
map.remove("1");
System.out.println("removed");
}
It produces java.util.ConcurrentModificationException
How can I avoid it ?