HashMap源代码----put与扩容机制

hashmap(jdk1.8)扩容机制:
hashmap在实例化时(new HashMap())时,只初始化了扩张因子
 
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted  默认值为0.75
}
向hashmap中添加元素时,主要使用方法 put(K, V);
源代码如下:
/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return the previous value associated with <tt>key</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 *         (A <tt>null</tt> return can also indicate that the map
 *         previously associated <tt>null</tt> with <tt>key</tt>.)
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
 
/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)            //如果hashmap刚初始化,不含有任何元素时
        n = (tab = resize()).length;                       //执行resize()方法,来初始化tab
    if ((p = tab[i = (n - 1) & hash]) == null)                  //如果table在该下标下为null,则new一个node并赋值给该值
        tab[i] = newNode(hash, key, value, null);
    else {                                       //否则就往后继续添加,链表的形式添加
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)                                //如果当前size大于阀值,则就进行扩容操作
        resize();
    afterNodeInsertion(evict);
    return null;
}
 
 
 
/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;                                      //获取原来的table
    int oldCap = (oldTab == null) ? 0 : oldTab.length;                         //获取node数组长度
    int oldThr = threshold;                                         //获取原有的阀值
    int newCap, newThr = 0;                                        //变量:存储新table的大小,新阀值的大小
    if (oldCap > 0) {                                            //如果已有node数组存在,不为0说明数组是存在
        if (oldCap >= MAXIMUM_CAPACITY) {                                 //如果超过最大允许容量(1<<30),
            threshold = Integer.MAX_VALUE;                                //设定最大阀值为0x7fffffff
            return oldTab;                                         //返回原来的table数组
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&                         //node数组长度设置为*2
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1;                                      // double threshold    总容量*2
    }
    else if (oldThr > 0)                                           // initial capacity was placed in threshold  若实例化时,采用的有参的构造函数,会进这一步
        newCap = oldThr;                                           //设置原来的阀值作为新的数组长度
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;                                  //默认的初始化
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);               //16*扩展因子
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;                                             //重设阀值
    @SuppressWarnings({"rawtypes","unchecked"})
                                                         //初始化新的node数组,大小为扩展后的大小
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;                                    //注意此处,多线程情况下,若线程同时进行操作,复制数据速度不一致,就会造成数据丢失。
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

  

 
下面解释resize代码部分
该部分代码,主要将原数组中的数据移入新的数组中
紫色部分代码解释:
注: 在put时,数组下标的算法为 e.hash & (tabSize - 1),在扩容后,该算法不变,只是将tabSize更新为newTabSize
newTabSize = tabSize << 1,e.hash & oldCap == 0时,则e.hash & (newTabSize-1) = 0 + e.hash & (tabSize - 1)
                                              e.hash & oldCap != 0时,则e.hash & (newTabSize - 1) = oldCap + e.hash & (tabSize - 1)
 
举例:数组大小由    1 << 6(oldCap) 即 100 0000 扩容至 1 << 7(newCap)即 1000 0000
 
原数组上点 e.hash = p11 0001(p的值具体未知)
tabSize = 100 0000
newTabSize = 1000 0000
 
tabSize - 1 = 11 1111
newTabSize - 1 = 111 1111
 
所在的原数组下标  e.hash & (tabSize - 1) = 11 0001 &
                                                   11 1111 = 11 0001
若 p为0
新数组下标: e.hash & (newTabSize - 1) = 011 0001 &
                                                111 1111 = 011 0001 = 0 + 11 0001 = 0 + e.hash & (tabSize - 1)
若p为1
新数组下标: e.hash & (newTabSize - 1) = 111 0001 &
                                                111 1111 = 111 0001 = 1 << 6 + 11 0001 = oldCap + e.hash & (tabSize - 1)
 
从上述推导可以看出: e.hash & oldCap目的是为了计算e.hash与oldCap最高位(1)“与”运算的值,从而推算出p的值
 
同时也分为p为0或1的两种处理情况,对map中的所有元素重新遍历计算后,将其填进新node数组,完成扩容
 
从put操作中,我们可以看出,hashmap是thread-unsafe
特别是在扩容时,我们会发现,若两个线程同时进行扩容,就会造成数据丢失。因为扩容时,都涉及到重新分配至新数组。
如:A、B线程都进行写操作,两者均发现要超阀值,就进行扩容操作,但hashmap的扩容机制是重新分配至新数组,再将该新数组作为hashmap对象的table数组,这样就只会返回最后进行扩容的数组,这样就会导致其中一个线程的数据丢失。(因为在扩容时,会将原有数组下数据进行释放oldTab[j] =null)
posted @ 2017-07-21 09:43  天地由我欣  阅读(216)  评论(0)    收藏  举报