HashMap 與 ConcurrentHashMap


1. HashMap

1) 並發問題

HashMap的並發問題源於多線程訪問HashMap時, 如果存在修改Map的結構的操作(增刪, 不包括修改), 則有可能會發生並發問題, 表現就是get()操作會進入無限循環

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

究其原因, 是因為 getEntry 先獲取了 table 中的鏈表, 而鏈表是一個循環鏈表, 所以進入了無限循環, 在正常情況下, 鏈表並不會出現循環的情況

出現這種情況是在多線程進行put的時候, 因為put會觸發resize(rehash)操作, 當多個rehash同時發生時, 鏈表就有可能變得錯亂, 變成一個循環鏈表

    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }

void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable, initHashSeedAsNeeded(newCapacity)); // transfer 方法對所有Entry進行了rehash
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

多線程resize的時候會同時創建多個newTable, 然后同時rehash, 造成鏈表錯亂

另外rehash對於hashmap的性能代價也是相當大的, 所以選擇一個合適的table長度也是很重要的

2) iterator 與 fail-fast

 遍歷的兩種方法

for (int i = 0; i < collection.size(); i++) {
    T t = collection.get(i) 
    // ...
}

for (T t : collection) {
   // ...
}

 

為什么使用iterator, 是因為有的數據結構 get(i) 的效率是O(n), 而非O(1), 例如 LinkedList, 那么整個循環的效率則會變為 O(n2)

iterator內部使用fail-fast機制來提醒並發問題的發生, 例如在遍歷的時候同時修改map, 則會拋出ConcurrentModificationException異常

for (Entry<K, V> t : map) {
    map.remove(t.key);
    // Exception throw
}

 

之所以拋出異常是因為在遍歷的時候同時修改map, 會導致一些意想不到的情況發生

1) remove 操作. 

假如在遍歷的時候進行remove , 則有可能拿到的當前元素變為空, 導致遍歷無法往下進行, 而直接跳到hashMap table的下一個槽位, 丟失整個槽位的鏈表數據

    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
           e = e.next) { // 例如這里的 e.next 在遍歷的時候被刪除, 則會導致這個槽位的元素全被跳過
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

 

 

2) put 操作

put操作的resize會導致table鏈表重新分配, 遍歷則會變得混亂, 不再贅述

 

2. ConcurrentHashMap

ConcurrentHashMap是HashMap的線程安全實現, 不同於HashTable, 他並不是用對整個HashMap使用synchronized來保證同步, 而是對map進行分段, 在插入時只使用重入鎖鎖定特定的段

這樣根據段位的數量則可以達到不同的並發數量, 所以在使用他時可以根據我們的並發線程來定制這個段的數量.

1) segment的數量是ssize = 1 << concurrencyLevel, 默認 DEFAULT_CONCURRENCY_LEVEL = 16

2) 每個segment的長度是 initialCapacity / ssize, 最小值為 MIN_SEGMENT_TABLE_CAPACITY = 2

同樣, 他的Iterator也不同於傳統的HashIterator, 他並不會拋出ConcurrentModificationException, 這是因為他的遍歷器的next()方法, 每次都是返回一個new的WriteThroughEntry, 這個東西保證了你在獲取到Entry以后即使Map遭到修改, 也不會影響你當前遍歷的結果. 但是, 如果你對WriteThroughEntry進行setValue操作, 還是可以影響到原來的map的, 代碼如下

final class EntryIterator
        extends HashIterator
        implements Iterator<Entry<K,V>>
    {
        public Map.Entry<K,V> next() {
            HashEntry<K,V> e = super.nextEntry();
            return new WriteThroughEntry(e.key, e.value);
        }
    }

/**
     * Custom Entry class used by EntryIterator.next(), that relays
     * setValue changes to the underlying map.
     */
    final class WriteThroughEntry
        extends AbstractMap.SimpleEntry<K,V>
    {
        WriteThroughEntry(K k, V v) {
            super(k,v);
        }

        /**
         * Set our entry's value and write through to the map. The
         * value to return is somewhat arbitrary here. Since a
         * WriteThroughEntry does not necessarily track asynchronous
         * changes, the most recent "previous" value could be
         * different from what we return (or could even have been
         * removed in which case the put will re-establish). We do not
         * and cannot guarantee more.
         */
        public V setValue(V value) {
            if (value == null) throw new NullPointerException();
            V v = super.setValue(value);
            ConcurrentHashMap.this.put(getKey(), value); // 將改變寫入到原來的map中 return v;
        }
    }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM