Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Hashtable 多線程遍歷時的 ConcurrentModificationException

最近程式常常丟出 java.util.ConcurrentModificationException。追查後發現,一個負責清理無用 key 的互斥線程每小時執行一次,用 iterator 遍歷,問題就出在這裡,結果導致 map 的值不斷增大、清理不起來。

問題成因

使用 iterator 遍歷時,不能在迴圈中呼叫原 Hashtable 的 put 或 remove,否則就會丟出 ConcurrentModificationException。加鎖雖然能解決,卻可能帶來效能問題——尤其這個清理動作每小時都要跑一次。

改用 Enumeration

測試後可行的寫法是換成 Enumeration:

Enumeration<String> e1 = T1.map.keys();
while (e1.hasMoreElements()) {
    String key = e1.nextElement();
    String ret = T1.map.remove(key);
}

差別在於 Enumeration 不做「修改次數」的一致性檢查,因此遍歷途中刪除不會被攔下。Hashtable 本身就是同步的,每個方法呼叫都各自加鎖,所以單就資料正確性而言並不會出錯。

測試程式

public class T1 extends Thread {
    public static Hashtable<String, String> map = new Hashtable<String, String>();

    public void run() {
        super.run();
        while (true) {
            for (int i = 0; i < 100; i++) {
                map.put(String.valueOf(System.currentTimeMillis()) + i, "");
            }
            System.out.println("add 100---->" + map.size());
            Random rd = new Random();
            try {
                Thread.sleep(rd.nextInt(10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        t1.start();
        T2 t2 = new T2();
        t2.start();
    }
}

public class T2 extends Thread {

    public void run() {
        super.run();
        while (true) {
            System.out.println("map----size 01:" + T1.map.size());
            // 會發生例外的邏輯
            // Iterator it = T1.map.entrySet().iterator();
            // while (it.hasNext()) {
            //     it.next();
            //     it.remove();
            // }

            Enumeration<String> e1 = T1.map.keys();
            while (e1.hasMoreElements()) {
                String key = e1.nextElement();
                String ret = T1.map.remove(key);
            }

            System.out.println("map----size 02:" + T1.map.size());

            Random rd = new Random();
            try {
                Thread.sleep(rd.nextInt(10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

補充一個觀念:Hashtable 的方法級同步只保證單次操作安全,若要「讀取後再刪除」這類複合動作,仍須自己在外部 synchronized。若專案可以升級,ConcurrencyHashMap 搭配 iterator 的弱一致性遍歷會是更乾淨的選擇,邊遍歷邊刪除不會丟例外,也不必犧牲並行度。

Copyright © Linux教程網 All Rights Reserved