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

Hashtable 遍歷拋出 ConcurrentModificationException 的真相

本文涵蓋

  • Hashtable 及其內部類的部分源碼分析
  • Hashtable 遍歷時 java.util.ConcurrentModificationException 的成因與解法
  • 單機記憶體快取並定期清除過期資料的簡單實作

事情的起因

工作中需要在某個業務類裡做一個把物件快取在記憶體中的機制(單機),於是有了下面這種結構:

package org.cnblog.test;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * JAVA 的 Hashtable 在遍歷時的迭代器線程問題
 */
public class HashtableIteratorTest {

    // 初始化快取,並啟動刷新快取的線程
    static {
        Cache.cacheMap = new Hashtable<String, Long>();
        new Cache().start();
    }

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    long time = System.currentTimeMillis();
                    Cache.cacheMap.put(time + "", time);
                    System.out.println("[" + Thread.currentThread().getName() + "]Cache 中新增快取>>" + time);
                    try {
                        Thread.sleep(1 * 1000); // 每秒增加一個快取
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }

    private static class Cache extends Thread {
        private static Hashtable<String, Long> cacheMap;

        /** 刷新快取:清除停留超過 10 秒的內容 */
        private void refresh() {
            synchronized (cacheMap) {
                String key;
                Iterator<String> i = cacheMap.keySet().iterator();
                while (i.hasNext()) {
                    key = i.next();
                    if (cacheMap.get(key) != null && System.currentTimeMillis() - cacheMap.get(key) > 10 * 1000) {
                        cacheMap.remove(key);
                        System.out.println("[" + Thread.currentThread().getName() + "]刪除的 Key 值<<" + key);
                    }
                }
            }
        }

        public void run() {
            while (true) {
                refresh();
                try {
                    Thread.sleep(10 * 1000); // 每 10 秒刷新一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

結構說明:業務類用靜態內部類 Cache 存放快取,快取的直接載體是內部類的靜態成員 cacheMap;Cache 是線程類,每 10 秒刷新一次(清掉停留超過 10 秒的內容);main 方法模擬每秒寫入一個快取。

於是問題來了:

[Thread-1]Cache 中新增快取>>1418207644572
...
[Thread-0]刪除的 Key 值<<1418207644572
Exception in thread "Thread-0" java.util.ConcurrentModificationException
    at java.util.Hashtable$Enumerator.next(Unknown Source)
    at org.cnblog.test.HashtableIteratorTest$Cache.refresh(HashtableIteratorTest.java:53)
    at org.cnblog.test.HashtableIteratorTest$Cache.run(HashtableIteratorTest.java:64)

也就是第 53 行迭代 cacheMap 時拋出了 ConcurrentModificationException。

追查過程

JDK 對這個異常的描述是:當方法檢測到對象的並發修改,但不允許這種修改時,拋出此異常。奇怪的是,我明明已經在 refresh() 中對 cacheMap 加了鎖,next() 時卻照樣爆掉。於是翻源碼。

cacheMap.keySet() 做了什麼:

public Set<K> keySet() {
    if (keySet == null) keySet = Collections.synchronizedSet(new KeySet(), this);
    return keySet;
}

KeySet 是 Set 的子類、Hashtable 的內部類,回傳的是被 Collections.synchronizedSet 包裝後的 SynchronizedSet 物件。SynchronizedSet 的部分源碼:

public <T> T[] toArray(T[] a) { synchronized(mutex) { return c.toArray(a); } }

public Iterator<E> iterator() {
    return c.iterator(); // Must be manually synched by user!
}

public boolean add(E e) { synchronized(mutex) { return c.add(e); } }
public boolean remove(Object o) { synchronized(mutex) { return c.remove(o); } }

這裡 c 是 KeySet 物件,mutex 是呼叫 keySet() 的物件,也就是 cacheMap。請特別注意 iterator() 裡那句註解:用戶必須手動同步。

取得迭代器時 cacheMap.keySet().iterator():最終回傳的是 Enumerator(Hashtable 的內部類),關鍵程式碼如下:

public T next() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    return nextElement();
}

public void remove() {
    if (!iterator) throw new UnsupportedOperationException();
    if (lastReturned == null) throw new IllegalStateException("Hashtable Enumerator");
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();

    synchronized(Hashtable.this) {
        Entry[] tab = Hashtable.this.table;
        int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;

        for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) {
            if (e == lastReturned) {
                modCount++;
                expectedModCount++;
                if (prev == null) tab[index] = e.next;
                else prev.next = e.next;
                count--;
                lastReturned = null;
                return;
            }
        }
        throw new ConcurrentModificationException();
    }
}

源頭找到了:只要 modCount != expectedModCount 就拋異常。

兩個計數器的含義:

  • modCount(int,位於外部類 Hashtable):記錄對 Hashtable 內部結構產生變化的操作次數,例如 rehash()、put(K, V) 中都有 modCount++。
  • expectedModCount(int,位於 Enumerator):迭代器建立時被賦予 modCount 當時的值,用於檢測並發修改;它在迭代器的 remove() 中與 modCount 一同自增。

於是真相清楚了:取得迭代器時兩者相等,但迴圈中第 55 行的 cacheMap.remove(key) 讓 modCount 自增 1,兩者不再相等,異常就此拋出。

結論

在 Hashtable 迭代過程中,除了迭代器自身的操作之外,任何會改變該 map 結構的操作都屬於並發修改,迭代器將無法正常工作。這就是這類異常的由來,而「加鎖同步兩個操作」並不是問題所在。

解法很簡單,把第 55 行用 map 刪除:

cacheMap.remove(key);

改成用迭代器刪除:

i.remove();

由此可推廣出兩條原則:要麼不要在迭代時進行 rehash()、put(K, V)、remove(Object key) 這類會改變結構的操作;要麼就把可能的操作都放在迭代器裡做。

Copyright © Linux教程網 All Rights Reserved