1. 程式人生 > >JDK1.7之 HashMap 原始碼分析

JDK1.7之 HashMap 原始碼分析

JDK1.7 及之前的版本中,HashMap中通過雜湊連結串列的形式來儲存資料,基於一個數組及多個連結串列的方式,當hash值衝突的時候,就會在對應的節點以連結串列的形式儲存這些hash值衝突的資料!

整個HashMap的原始碼實現主要應該關注的有以下幾點:

  • 擴容演算法

  • put()

  • get()

  • 為什麼HashMap不是執行緒安全的?

  • hash演算法

類繼承關係

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

建構函式

先來看幾個常量

/**
     * 初始容量為16。容量必須是2的指數倍
     */
    static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
     * 最大容量
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
/**
     * 載入因子預設是0.75.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

平衡因子的作用在於,當儲存的容量超過閾值(儲存容量和載入因子的乘積)時,要對雜湊表進行擴充套件操作。這個平衡因子的預設數值是JDK約定的。

    /**
     * 儲存鍵值對對應的Entry陣列
     */
    transient Entry<K,V>[] table;
    /**
     * 鍵值對的個數
     */
    transient int size;
    /**
     * 表示一個閾值,當size超過了threshold就會擴容
     */
    int threshold;
    /**
     * 載入因子
     */
    final float loadFactor;
    /**
     * map結構修改次數,累加
     */
transient int modCount;
    /**
     * 預設閾值
     */
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        // 找到一個大於等於initialCapacity並且是2的指數的值作為初始容量
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        // 初始化閾值
        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        // 初始化Entry陣列
        table = new Entry[capacity];
        useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        init();
    }
// 空實現
 void init() {
    }
// 傳進來一個Map儲存到HashMap中
public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        putAllForCreate(m);
    }
private void putAllForCreate(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) // 遍歷map
            putForCreate(e.getKey(), e.getValue()); 

            // putForCreate() 這裡先不說
    }

通過上面看到,建構函式的處理無非就是通過傳入的初始容量和載入因子(沒有則用預設值),然後出事化Entry陣列及其他一些變數。

建構函式先分析到這裡。

Entry

來看看Entry這是類的內容

// 靜態內部類
static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next; // 只想下一個entry節點
        int hash;

        /**
         * 建構函式,每次都用新的節點指向連結串列的頭結點。新節點作為連結串列新的頭結點
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n; // !!!
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return (key==null   ? 0 : key.hashCode()) ^
                   (value==null ? 0 : value.hashCode());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

從Entry的建構函式可以看出,每次建立新的Entry物件,就會把連結串列的頭結點作為next拼接到新的entry物件上。也就是說每次插入新的map資料時,就會在一個bucket的最前面(連結串列頭部)!

put

put()

/* 
 * 1. 通過key的hash值確定table下標 
 * 2. 查詢table下標,如果key存在則更新對應的value 
 * 3. 如果key不存在則呼叫addEntry()方法 
*/  
public V put(K key, V value) {
        if (key == null) 
            return putForNullKey(value);
        int hash = hash(key); // 重點!!!
        int i = indexFor(hash, table.length); // 查詢對應的陣列下標
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        // 沒有在相同hash值的連結串列中找到key相同的節點
        modCount++;
        addEntry(hash, key, value, i); // 在i位置對應的連結串列上新增一個節點
        return null;
    }

當key為null的時候呼叫了putForNullKey()函式。

可見HashMap可以put進去key值為null的資料。

從for迴圈的if判斷條件可以看出,如果key值有相同的資料則會覆蓋value值,可見HashMap中key值都是唯一的!

putForNullKey()

private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) { // 尋找陣列0位置對應的連結串列key值為null的節點,進而更新value值
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0); // 在陣列0位置對應的連結串列上新增一個節點
        return null;
    }

下面來看addEentry()

void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) { // 如果資料大小已經超過閾值並且陣列對應的bucket不為空,則需要擴容
            resize(2 * table.length); // 擴容
            hash = (null != key) ? hash(key) : 0; // key為null的時,hash值設為0
            bucketIndex = indexFor(hash, table.length); // 確定是哪一個連結串列(bucket下標)
        }

        createEntry(hash, key, value, bucketIndex);
    }
//判斷k的資料型別選擇不同的hash計算方式
final int hash(Object k) {
        int h = 0;
        if (useAltHashing) {
            if (k instanceof String) { // 如果k是Sting型別
                return sun.misc.Hashing.stringHash32((String) k);
            }
            h = hashSeed;
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

HashMap採用一個Entry陣列來儲存bucket 。一個bucket就代表一條hash相同的節點連結串列。

如下圖:

這裡寫圖片描述

接著上面的函式實現來分析。先不看resize()這個擴容演算法,先來看createEntry()

void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

putForCreate()

此方法用在建構函式、克隆或者反序列化的時候呼叫。不會調整table陣列的大小。

private void putForCreate(K key, V value) {
        int hash = null == key ? 0 : hash(key);
        int i = indexFor(hash, table.length);

        /**
         * 如果存在key值相同的節點,則更新value值
         */
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                e.value = value;
                return;
            }
        }
        // 否則建立新的entry加入某個bucket對應的連結串列中
        createEntry(hash, key, value, i);
    }

擴容

現在假設需要擴容,及資料量已經達到了閾值了。

// 
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]; // 建立新的陣列
        boolean oldAltHashing = useAltHashing;
        useAltHashing |= sun.misc.VM.isBooted() &&
                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean rehash = oldAltHashing ^ useAltHashing; // 是否需要重新計算hash值
        transfer(newTable, rehash);  // 將table的資料轉移到新的table中
        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) { //將這一個連結串列遍歷新增到新的陣列對應的bucket中
                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;
            }
        }
    }
    /**
     * 得到hash值在table陣列中的位置
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

get

    /**
     * 得到 key = null 對應的value值
     */
    private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }
    /**
     * 根據key得到對應的value值
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey(); // 如果key為null,則呼叫getForNullKey()
        Entry<K,V> entry = getEntry(key); // 重點在getEntry()函式

        return null == entry ? null : entry.getValue();
    }
    /**
     * 根據key得到對應的Entry物件
     */
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) { // 遍歷hash值相同(通過key得到)的那個bucket(連結串列)
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

remove

public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key); // !!!
        return (e == null ? null : e.value); // 返回key對應的value值
    }
final Entry<K,V> removeEntryForKey(Object key) {
        int hash = (key == null) ? 0 : hash(key); //計算hash值
        int i = indexFor(hash, table.length); // 得到下標
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++; // 操作次數+1
                size--;
                if (prev == e) // 如果是buckek的頭節點是要找的結點,直接將陣列指向next
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e; // 如果連結串列遍歷結束還是沒找到,則此時e為null,返回null
    }

clear

public void clear() {
        modCount++; // +1
        Entry[] tab = table;
        for (int i = 0; i < tab.length; i++)
            tab[i] = null;
        size = 0; // 置0
    }

hash()

每次put一個鍵值對或者,通過get得到一個值的時候,都會對key進行hash運算得到hash值

final int hash(Object k) {
        int h = 0;
        if (useAltHashing) {
            if (k instanceof String) {
                return sun.misc.Hashing.stringHash32((String) k);
            }
            h = hashSeed;
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);                                                                                          
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

通過上述函式得到hash值之後,在通過 indexFor()函式得到對應table陣列的下標!

static int indexFor(int h, int length) {
        return h & (length-1);
    }

舉個例子:

這裡寫圖片描述

通過二進位制的異或,移位,與 等操作,最後運算得到一個下標。

Fail-Fast

下面來關注一下modCount這本變數!

在put() 、remove()、 clear()的時候modCount都會進行+1操作。

對HashMap內容的修改都會增加這個值。

HashMap 通過拉鍊法實現的散列表,table陣列中的每一個Entry又是一個單鏈表!

看一下HashMap怎麼遍歷的:

private transient Set<Map.Entry<K,V>> entrySet = null; // 是一個集合
public Set<Map.Entry<K,V>> entrySet() {
        return entrySet0();
    }
private Set<Map.Entry<K,V>> entrySet0() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet()); // entrySet為空時new一個EntrySet物件
    }
private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return newEntryIterator();  // 建立迭代器
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry)) // 比較型別
                return false;
            Map.Entry<K,V> e = (Map.Entry<K,V>) o;
            Entry<K,V> candidate = getEntry(e.getKey());
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            return removeMapping(o) != null;
        }
        public int size() {
            return size;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }

其實HashMap內部由三種迭代器

    Iterator<K> newKeyIterator()   { // key迭代器
        return new KeyIterator();
    }
    Iterator<V> newValueIterator()   { // value迭代器
        return new ValueIterator();
    }
    Iterator<Map.Entry<K,V>> newEntryIterator()   { // entry迭代器
        return new EntryIterator();
    }

而這三種迭代器又都繼承 HashIterator

    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }
// hash迭代器
private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry<K,V> current;     // current entry

        HashIterator() {
            expectedModCount = modCount; // 臨時儲存
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        // 每次迭代都會呼叫次函式得到下一個Entry物件
        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount) // 判斷
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount) // 判斷
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
    }

在迭代的過程中,如果發現modCount != expectedModCount,那麼就表示有其他的執行緒對HashMap進行了修改操作,進而就丟擲 ConcurrentModificationException 這個異常!

所以:HashMap是非執行緒安全的!

小結

從上面的分析可以得到以下結論:

  • HashMap的value可以為null

  • HashMap是非執行緒安全的

  • 初始容量和載入因子會影響HashMap的效能

參考