This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
                                
                                    (24个答案)
                                
                        
                4年前关闭。
            
        

下面的代码给出了当我多次运行以下代码ConcurrentModificationException时的情况。
当我使用非concurrentHashMap时,它工作正常。

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


我所缺少的。

最佳答案

ConcurrentHashMap不同,通过Map习惯进行初始化时,例如,您需要显式同步Collections.synchronizedMap。使用synchronized关键字。

docs


  当迭代其任何集合视图时,用户必须在返回的地图上手动进行同步:[...]

关于java - Java集合synchronizedMap无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33412583/

10-12 06:22