简体   繁体   English

如何在迭代 map.entrySet 时避免 ConcurrentModificationException

[英]How to avoid ConcurrentModificationException while iterating over map.entrySet

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它产生java.util.ConcurrentModificationException

How can I avoid it ?我怎样才能避免它?

you could use static final Map<String, String> map = new ConcurrentHashMap<>();你可以使用static final Map<String, String> map = new ConcurrentHashMap<>();

    static final Map<String, String> map = new ConcurrentHashMap<>();

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

You cannot remove an element from a collection while iterating it, unless you use an Iterator.迭代时不能从集合中删除元素,除非使用 Iterator。 Use Iterator.remove() method使用 Iterator.remove() 方法

If you want to iterate over a Collections.synchronizedMap you must explicitly synchronize the iteration:如果要迭代Collections.synchronizedMap ,则必须显式同步迭代:

        synchronized (map) {
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                System.out.println("after iterator");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
         }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM