微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HashMap源码解析,JVM发生内存溢出的8种原因

this.loadFactor = loadFactor;

//返回2的幂次方

this.threshold = tableSizefor(initialCapacity);

}

复制代码




对于上面的构造器,我们需要注意的是`this.threshold = tableSizefor(initialCapacity);`这边的 threshold 为 2的幂次方,而不是`capacity * load factor`,当然此处并非是错误,因为此时 table 并没有真正的被初始化,初始化动作被延迟到了`putVal()`当中,所以 threshold 会被重新计算。



/**

  • 根据指定的容量以及负载因子(0.75)初始化一个空的 HashMap 实例

  • 如果 initCapacity是负数,那么将抛出 IllegalArgumentException

*/

public HashMap(int initialCapacity) {

this(initialCapacity, DEFAULT_LOAD_FACTOR);

}

/**

*/

public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

}

/**

  • Constructs a new HashMap with the same mappings as the

  • specified Map. The HashMap is created with

  • default load factor (0.75) and an initial capacity sufficient to

  • hold the mappings in the specified Map.

  • @param m the map whose mappings are to be placed in this map

  • @throws NullPointerException if the specified map is null

*/

public HashMap(Map<? extends K, ? extends V> m) {

this.loadFactor = DEFAULT_LOAD_FACTOR;

putMapEntries(m, false);

}

复制代码




### 查询



/**

  • 返回指定 key 所对应的 value 值,当不存在指定的 key 时,返回 null。

  • 当返回 null 的时候并不表明哈希表中不存在这种关系的映射,有可能对于指定的 key,其对应的值就是 null。

  • 因此可以通过 containsKey 来区分这两种情况。

*/

public V get(Object key) {

Node<K,V> e;

return (e = getNode(hash(key), key)) == null ? null : e.value;

}

/**

  • 1.首先通过 key 的哈希值找到其所在的哈希桶

  • 2.对于 key 所在的哈希桶只有一个元素,此时就是 key 对应的节点,

  • 3.对于 key 所在的哈希桶超过一个节点,此时分两种情况:

  • 如果这是一个 TreeNode,表明通过红黑树存储,在红黑树中查找
    
  • 如果不是一个 TreeNode,表明通过链表存储(链地址法),在链表中查找
    
  • 4.查找不到相应的 key,返回 null

*/

final Node<K,V> getNode(int hash, Object key) {

Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

if ((tab = table) != null && (n = tab.length) > 0 &&

    (first = tab[(n - 1) & hash]) != null) {

    if (first.hash == hash && // always check first node

        ((k = first.key) == key || (key != null && key.equals(k))))

        return first;

    if ((e = first.next) != null) {

        if (first instanceof TreeNode)

            return ((TreeNode<K,V>)first).getTreeNode(hash, key);

        do {

            if (e.hash == hash &&

                ((k = e.key) == key || (key != null && key.equals(k))))

                return e;

        } while ((e = e.next) != null);

    }

}

return null;

}

复制代码




### 存储



/**

  • 在映射中,将指定的键与指定的值相关联。如果映射关系之前已经有指定的键,那么旧值就会被替换

*/

public V put(K key, V value) {

return putVal(hash(key), key, value, false, true);

}

/**

    • @param onlyIfAbsent if true, don’t change existing value
  • 1.判断哈希表 table 是否为空,是的话进行扩容操作

  • 2.根据键 key 计算得到的 哈希桶数组索引,如果 table[i] 为空,那么直接新建节点

  • 3.判断 table[i] 的首个元素是否等于 key,如果是的话就更新旧的 value 值

  • 4.判断 table[i] 是否为 TreeNode,是的话即为红黑树,直接在树中进行插入

  • 5.遍历 table[i],遍历过程发现 key 已经存在,更新旧的 value 值,否则进行插入操作,插入后发现链表长度大于8,则将链表转换为红黑树

*/

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

           boolean evict) {

Node<K,V>[] tab; Node<K,V> p; int n, i;

//哈希表 table 为空,进行扩容操作

if ((tab = table) == null || (n = tab.length) == 0)

    n = (tab = resize()).length;

// tab[i] 为空,直接新建节点

if ((p = tab[i = (n - 1) & hash]) == null)

    tab[i] = newNode(hash, key, value, null);

else {

    Node<K,V> e; K k;

    //tab[i] 首个元素即为 key,更新旧值

    if (p.hash == hash &&

        ((k = p.key) == key || (key != null && key.equals(k))))

        e = p;

    //当前节点为 TreeNode,在红黑树中进行插入

    else if (p instanceof TreeNode)

        e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

    else {

        //遍历 tab[i],key 已经存在,更新旧的 value 值,否则进心插入操作,插入后链表长度大于8,将链表转换为红黑树

        for (int binCount = 0; ; ++binCount) {

            if ((e = p.next) == null) {

                p.next = newNode(hash, key, value, null);

                //链表长度大于8

                if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

                    treeifyBin(tab, hash);

                break;

            }

            // key 已经存在

            if (e.hash == hash &&

                ((k = e.key) == key || (key != null && key.equals(k))))

                break;

            p = e;

        }

    }

    //key 已经存在,更新旧值

    if (e != null) { // existing mapping for key

        V oldValue = e.value;

        if (!onlyIfAbsent || oldValue == null)

            e.value = value;

        afterNodeAccess(e);

        return oldValue;

    }

}

//HashMap插入元素表明进行了结构性调整

++modCount;

//实际键值对数量超过 threshold,进行扩容操作

if (++size > threshold)

    resize();

afterNodeInsertion(evict);

return null;

}

复制代码




### 扩容



/**

  • 初始化或者对哈希表进行扩容操作。如果当前哈希表为空,则根据字段阈值中的初始容量进行分配。

  • 否则,因为我们扩容两倍,那么对于桶中的元素要么在原位置,要么在原位置再移动2次幂的位置。

*/

final Node<K,V>[] resize() {

Node<K,V>[] oldTab = table;

int oldCap = (oldTab == null) ? 0 : oldTab.length;

int oldThr = threshold;

int newCap, newThr = 0;

if (oldCap > 0) {

    //超过最大容量,不再进行扩容

    if (oldCap >= MAXIMUM_CAPACITY) {

        threshold = Integer.MAX_VALUE;

        return oldTab;

    }

    //容量没有超过最大值,容量变为原来两倍

    else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&

             oldCap >= DEFAULT_INITIAL_CAPACITY)

        //阈值变为原来两倍

        newThr = oldThr << 1; // double threshold

}

else if (oldThr > 0) // initial capacity was placed in threshold

    //调用了HashMap的带参构造器,初始容量用threshold替换,

    //在带参构造器中,threshold的值为 tableSizefor() 的返回值,也就是2的幂次方,而不是 capacity * load factor

    newCap = oldThr;

else {               // zero initial threshold signifies using defaults

    //初次初始化,容量和阈值使用认值

    newCap = DEFAULT_INITIAL_CAPACITY;

    newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

}

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<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) {

            //将原哈希桶置空,以便GC

            oldTab[j] = null;

            //当前节点不是以链表形式存在,直接计算其应放置的新位置

            if (e.next == null)

                newTab[e.hash & (newCap - 1)] = e;

            //当前节点是TreeNode

            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;

                    }

                    //原索引 + oldCap

                    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;

}

复制代码






# 总结

本文从基础到高级再到实战,由浅入深,把MysqL讲的清清楚楚,明明白白,这应该是我目前为止看到过最好的有关MysqL的学习笔记了,我相信如果你把这份笔记认真看完后,无论是工作中碰到的问题还是被面试官问到的问题都能迎刃而解!

**[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](

)**

**MysqL50道高频面试题整理:**

] = loHead;

                    }

                    if (hiTail != null) {

                        hiTail.next = null;

                        newTab[j + oldCap] = hiHead;

                    }

                }

            }

        }

    }

    return newTab;

}

复制代码

总结

本文从基础到高级再到实战,由浅入深,把MysqL讲的清清楚楚,明明白白,这应该是我目前为止看到过最好的有关MysqL的学习笔记了,我相信如果你把这份笔记认真看完后,无论是工作中碰到的问题还是被面试官问到的问题都能迎刃而解!

**[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](

)**

MysqL50道高频面试题整理:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐