0

Below code gives when I run the below code multiple time ConcurrentModificationException. When I use non concurrentHashMap it is working fine.

    public static void main(String[] args) {

        Map<String, String> stringSyncedMap = Collections.synchronizedMap(new HashMap<String, String>());

        CollectionJob collectionJob1 = new CollectionJob(stringSyncedMap, "read");
        CollectionJob collectionJob2 = new CollectionJob(stringSyncedMap, "write");

        Thread thread1 = new Thread(collectionJob1, "T1");
        Thread thread2 = new Thread(collectionJob2, "T2");

        thread1.start();
        thread2.start();
    }

}

public class CollectionJob implements Runnable {

    private Map<String, String> stringCollection;
    private String operation;

    public CollectionJob(Map<String, String> stringCollection, String operation) {

        this.stringCollection = stringCollection;
        this.operation = operation;
    }

    public void run() {

        if (operation.equals("read"))
            readFromCollection();
        else
            writeToCollection();

        System.out.println("done");

    }

    public void writeToCollection() {
        for (int i = 10; i < 20; i++) {
            stringCollection.put("String " + i, "String"+i);

    }

    public void readFromCollection() {
        for (String str : stringCollection.keySet()) 
            System.out.println(str);
    }
}

What I am missing.

Eran
  • 387,369
  • 54
  • 702
  • 768
arham
  • 167
  • 1
  • 3
  • Note that `ConcurrentHashMap` explicitly protects against `ConcurrentModificationException` (returning a "view" of the collection) unlike most of the other collections. – Kayaman Oct 29 '15 at 11:14
  • You are not using a `ConcurrentHashMap` in your code. That's a different thing than what `Collections.synchronizedMap` returns. – Manos Nikolaidis Oct 29 '15 at 11:16
  • @Kayaman That duplicate isn't really relevant. Ths question is about the difference between ConcurrentHashMap and Collections.synchronizedMap – Paul Boddington Oct 29 '15 at 11:17
  • @PaulBoddington I'd say it's definitely relevant, even though it's not the exact duplicate. His title also indicates that he probably doesn't know what `ConcurrentModificationException` is. You could vote to reopen? – Kayaman Oct 29 '15 at 11:20

1 Answers1

2

Unlike ConcurrentHashMap, you need to explicitly synchronize over your Map when initialized through the Collections.synchronizedMap idiom, e.g. using the synchronized keyword.

From the docs:

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views: [...]

Mena
  • 47,782
  • 11
  • 87
  • 106