迭代map.entrySet时如何避免ConcurrentModificationException

时间:2016-03-28 14:13:33

标签: java dictionary iterator concurrentmodification

我有以下代码:

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

它产生java.util.ConcurrentModificationException

我该如何避免呢?

3 个答案:

答案 0 :(得分:1)

您可以使用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");
}

答案 1 :(得分:0)

除非使用Iterator,否则在迭代时无法从集合中删除元素。使用Iterator.remove()方法

答案 2 :(得分:0)

如果要迭代public void getexactrow(String QuestionID){ this._QuestionID=QuestionID; SQLiteDatabase db = getWritableDatabase(); String colomn1 = "SELECT " +COLUMN_PRODUCTNAME+ " FROM " + TABLE_PRODUCTS + " WHERE 1"; String colomn2 = "SELECT " +COLUMN_ANSWER+ " FROM " + TABLE_PRODUCTS + " WHERE 1"; Cursor c1 = db.rawQuery(colomn1, null); Cursor c2 = db.rawQuery(colomn2, null); c1.move(Integer.parseInt(_QuestionID)); c2.move(Integer.parseInt(_QuestionID)); if (c1.getString(c1.getColumnIndex("productname")) != null) { _SendQuestion = c1.getString(c1.getColumnIndex("productname")); } if (c2.getString(c2.getColumnIndex("answer")) != null) { _SendAnswer = c2.getString(c2.getColumnIndex("answer")); } } ,则必须显式同步迭代:

Collections.synchronizedMap