HashMap explain initiate

Copyright: personal essays, problems at work, only to save the document, hoping to help you, please correct me if wrong with progress! Thank you! https://blog.csdn.net/w893932747/article/details/90271022

1, HashMap properties

  • HashMap is a hash bucket (linked lists and arrays), it stores the contents of the key-value is the key map
  • HashMap arrays and data structures using the linked list, and inherit the linear search list array and easy to modify the query modification addressing
  • HashMap non-synchronized, so soon HashMap
  • HashMap acceptable null keys and values, but can not Hashtable (reason is equlas () method requires the object, because after the HashMap is the API can only be treated)

2. What is the working principle of HashMap?

HashMap is based on the principle of hashing

We use the put (key, value) storage object to the HashMap using get (key) Gets an object from a HashMap. When we pass the keys and values ​​to the put () method, we first call to the key hashCode () method to calculate and return the hashCode is used to find the location Map bucket to store an array of Node objects.

The key point is noted here, the HashMap is to store key object in the bucket and the object values, as Map.Node.

HashMap is a combination of an array plus chain. As shown below:

 

Paste_Image.png

As can be seen in FIG HashMap underlying structure is an array, and each array stored list (list of references)

JDK1.6 achieve hashmap way is to use bit bucket (array) + linked list, i.e., the hash linked list. JDK1.8 bit barrel is the use of linked list + / red-black tree, i.e. when the chain length of a bit in the tub reaches a certain threshold (8), when the list is converted into a red-black tree, so greatly reducing the lookup time.

The following is a HashMap initialization

Simplified Analog data structure:

1

2

3

4

5

6

7

Node[] table = new Node[16]; // 散列桶初始化,table

class Node {

    hash; //hash值

    key; //键

    value; //值

    node next; //用于指向链表的下一层(产生冲突,用拉链法)

}

Find a store principle:

  • Storage: the first acquired hashCode key, modulo the length of the array and so can quickly locate the coordinates to be stored in the array, the array is then determined whether the storage element, if it is not stored, the newly constructed Node node, the node Node stored in the array, if there are elements, then iterate over the (red-black binary tree), if there is this key, update the default value, put the newly built Node storage to the end of the list does not exist.
  • Find: Ibid, obtaining the key hashcode, by taking the length of the mold hashcode array, to obtain the coordinates of the positioning elements, then the iteration list, for each key equals a compare element, the element if the same is returned.

When HashMap same number of elements, the greater the length of the array, the lower the Hash collision rate, the higher the efficiency of the reading, the smaller the length of the array, the collision rate, slower reading speed. Typical examples of space for time.

The following are specific put procedure (JDK1.8)

  1. Key requirements for the Hash value, and then calculates the subscript
  2. If there is no collision, directly into the bucket (the same meaning collision Hash value calculated by the need to put in the same bucket)
  3. If a collision to the list of ways to link back
  4. If the chain length exceeds the threshold value (TREEIFY THRESHOLD == 8), put into a red-black tree list turn, less than the length of the chain 6, put back black tree list
  5. If the node already exists replaces the old value
  6. If the bucket is full (capacity load factor 16 * 0.75), we need to resize (2-fold expansion after rearrangement)

Here's get the process

Consider a special case: if hashcode two keys are the same, how do you get the value of the object?

After the call when we get () method, HashMap uses the key object hashcode find bucket position, find the bucket position, will call keys.equals () method to find the correct node in the list, and ultimately I find the value of the object.

3. Is there any way to reduce the impact?

Perturbation function can reduce collisions

The principle is if two unequal objects return a different hashcode, then the probability of collisions will be smaller. This means that the deposit list structure is reduced, so the value would not have been frequent calls equal method to improve the performance of HashMap (ie internal disturbance Hash algorithm method, the purpose is to allow different objects return a different hashcode).

Immutable, the final declaration for the object, and using the appropriate equals () and hashCode () method will reduce collision

Non-denaturing buffer hashcode enables different keys, which will improve the overall speed of the object acquired using String, Integer wrapper classes such as the key is a very good choice.

Why String, Integer wrapper class for such a key?

Because String is final, and has rewritten the equals () and hashCode () method has. Immutability is necessary because in order to calculate the hashCode (), is necessary to prevent key change, returning different hashcode if put in the time and get the key, then do not find the object you want from the HashMap.

4, HashMap the hash function is how to achieve?

We can see that in hashmap you want to find an element, it is necessary to obtain the corresponding location in the array based on the hash value of the key. This is how to calculate the position of the hash algorithm.

As mentioned above, the data structure is hashmap binding arrays and linked list, of course, we hope to uniform distribution of the positions of these elements hashmap inside, as far as possible so that the number of elements in each position is only one. So when we find this position when using hash algorithm, you can immediately know the location of the corresponding elements of what we want, and not have to traverse the list. So, our first thought is to hashcode for array length modulo operation. As a result, the distribution of the elements is relatively uniform.

But the "mode" of operation consumption is quite large, you can not find a faster, consume less way? Let's look at JDK1.8 source code is how to do it (the landlord was modified a bit)

1

2

3

4

5

6

7

8

9

10

11

static final int hash(Object key) {

    if (key == null){

        return 0;

    }

    int h;

    h = key.hashCode();返回散列值也就是hashcode

    // ^ :按位异或

    // >>>:无符号右移,忽略符号位,空位都以0补齐

    //其中n是数组的长度,即Map的数组部分初始化长度

    return (n-1)&(h ^ (h >>> 16));

}

It is simply:

  • 高16 bit 不变,低16 bit 和高16 bit 做了一个异或(得到的 hashcode 转化为32位二进制,前16位和后16位低16 bit和高16 bit做了一个异或)
  • (n·1) & hash = -> 得到下标

5、拉链法导致的链表过深,为什么不用二叉查找树代替而选择红黑树?为什么不一直使用红黑树?

之所以选择红黑树是为了解决二叉查找树的缺陷:二叉查找树在特殊情况下会变成一条线性结构(这就跟原来使用链表结构一样了,造成层次很深的问题),遍历查找会非常慢。而红黑树在插入新数据后可能需要通过左旋、右旋、变色这些操作来保持平衡。引入红黑树就是为了查找数据快,解决链表查询深度的问题。我们知道红黑树属于平衡二叉树,为了保持“平衡”是需要付出代价的,但是该代价所损耗的资源要比遍历线性链表要少。所以当长度大于8的时候,会使用红黑树;如果链表长度很短的话,根本不需要引入红黑树,引入反而会慢。

6、说说你对红黑树的见解?

  1. 每个节点非红即黑
  2. 根节点总是黑色的
  3. 如果节点是红色的,则它的子节点必须是黑色的(反之不一定)
  4. 每个叶子节点都是黑色的空节点(NIL节点)
  5. 从根节点到叶节点或空子节点的每条路径,必须包含相同数目的黑色节点(即相同的黑色高度)

7、解决 hash 碰撞还有那些办法?

开放定址法

当冲突发生时,使用某种探查技术在散列表中形成一个探查(测)序列。沿此序列逐个单元地查找,直到找到给定的地址。按照形成探查序列的方法不同,可将开放定址法区分为线性探查法、二次探查法、双重散列法等。

下面给一个线性探查法的例子:

问题:已知一组关键字为 (26,36,41,38,44,15,68,12,06,51),用除余法构造散列函数,用线性探查法解决冲突构造这组关键字的散列表。
解答:为了减少冲突,通常令装填因子 α 由除余法因子是13的散列函数计算出的上述关键字序列的散列地址为 (0,10,2,12,5,2,3,12,6,12)。
前5个关键字插入时,其相应的地址均为开放地址,故将它们直接插入 T[0]、T[10)、T[2]、T[12] 和 T[5] 中。
当插入第6个关键字15时,其散列地址2(即 h(15)=15%13=2)已被关键字 41(15和41互为同义词)占用。故探查 h1=(2+1)%13=3,此地址开放,所以将 15 放入 T[3] 中。
当插入第7个关键字68时,其散列地址3已被非同义词15先占用,故将其插入到T[4]中。
当插入第8个关键字12时,散列地址12已被同义词38占用,故探查 hl=(12+1)%13=0,而 T[0] 亦被26占用,再探查 h2=(12+2)%13=1,此地址开放,可将12插入其中。
类似地,第9个关键字06直接插入 T[6] 中;而最后一个关键字51插人时,因探查的地址 12,0,1,…,6 均非空,故51插入 T[7] 中。

8、如果 HashMap 的大小超过了负载因子(load factor)定义的容量怎么办?

HashMap 默认的负载因子大小为0.75。也就是说,当一个 Map 填满了75%的 bucket 时候,和其它集合类一样(如 ArrayList 等),将会创建原来 HashMap 大小的两倍的 bucket 数组来重新调整 Map 大小,并将原来的对象放入新的 bucket 数组中。这个过程叫作 rehashing

因为它调用 hash 方法找到新的 bucket 位置。这个值只可能在两个地方,一个是原下标的位置,另一种是在下标为 <原下标+原容量> 的位置。

9、重新调整 HashMap 大小存在什么问题吗?

重新调整 HashMap 大小的时候,确实存在条件竞争。

因为如果两个线程都发现 HashMap 需要重新调整大小了,它们会同时试着调整大小。在调整大小的过程中,存储在链表中的元素的次序会反过来。因为移动到新的 bucket 位置的时候,HashMap 并不会将元素放在链表的尾部,而是放在头部。这是为了避免尾部遍历(tail traversing)。如果条件竞争发生了,那么就死循环了。多线程的环境下不使用 HashMap。

为什么多线程会导致死循环,它是怎么发生的?

HashMap 的容量是有限的。当经过多次元素插入,使得 HashMap 达到一定饱和度时,Key 映射位置发生冲突的几率会逐渐提高。这时候, HashMap 需要扩展它的长度,也就是进行Resize。

  1. 扩容:创建一个新的 Entry 空数组,长度是原数组的2倍
  2. rehash:遍历原 Entry 数组,把所有的 Entry 重新 Hash 到新数组

(这个过程比较烧脑,暂不作流程图演示,有兴趣去看看我的另一篇博文“HashMap扩容全过程”)

达摩:哎呦,小老弟不错嘛~~意料之外呀
小鲁班:嘿嘿,优秀吧,中场休息一波,我先喝口水
达摩:不仅仅是这些哦,面试官还会问你相关的集合类对比,比如:

10、HashTable

  • 数组 + 链表方式存储
  • 默认容量:11(质数为宜)
  • put操作:首先进行索引计算 (key.hashCode() & 0x7FFFFFFF)% table.length;若在链表中找到了,则替换旧值,若未找到则继续;当总元素个数超过 容量 * 加载因子 时,扩容为原来 2 倍并重新散列;将新元素加到链表头部
  • 对修改 Hashtable 内部共享数据的方法添加了 synchronized,保证线程安全

11、HashMap 与 HashTable 区别

  • 默认容量不同,扩容不同
  • 线程安全性:HashTable 安全
  • 效率不同:HashTable 要慢,因为加锁

12、可以使用 CocurrentHashMap 来代替 Hashtable 吗?

  • 我们知道 Hashtable 是 synchronized 的,但是 ConcurrentHashMap 同步性能更好,因为它仅仅根据同步级别对 map 的一部分进行上锁
  • ConcurrentHashMap 当然可以代替 HashTable,但是 HashTable 提供更强的线程安全性
  • 它们都可以用于多线程的环境,但是当 Hashtable 的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间。由于 ConcurrentHashMap 引入了分割(segmentation),不论它变得多么大,仅仅需要锁定 Map 的某个部分,其它的线程不需要等到迭代完成才能访问 Map。简而言之,在迭代的过程中,ConcurrentHashMap 仅仅锁定 Map 的某个部分,而 Hashtable 则会锁定整个 Map

13、CocurrentHashMap(JDK 1.7)

  • CocurrentHashMap 是由 Segment 数组和 HashEntry 数组和链表组成
  • Segment 是基于重入锁(ReentrantLock):一个数据段竞争锁。每个 HashEntry 一个链表结构的元素,利用 Hash 算法得到索引确定归属的数据段,也就是对应到在修改时需要竞争获取的锁。ConcurrentHashMap 支持 CurrencyLevel(Segment 数组数量)的线程并发。每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment
  • 核心数据如 value,以及链表都是 volatile 修饰的,保证了获取时的可见性
  • 首先是通过 key 定位到 Segment,之后在对应的 Segment 中进行具体的 put 操作如下:
    • 将当前 Segment 中的 table 通过 key 的 hashcode 定位到 HashEntry。
    • 遍历该 HashEntry,如果不为空则判断传入的  key 和当前遍历的 key 是否相等,相等则覆盖旧的 value
    • 不为空则需要新建一个 HashEntry 并加入到 Segment 中,同时会先判断是否需要扩容
    • 最后会解除在 1 中所获取当前 Segment 的锁。
  • 虽然 HashEntry 中的 value 是用 volatile 关键词修饰的,但是并不能保证并发的原子性,所以 put 操作时仍然需要加锁处理

首先第一步的时候会尝试获取锁,如果获取失败肯定就有其他线程存在竞争,则利用 scanAndLockForPut() 自旋获取锁。

  • 尝试自旋获取锁
  • 如果重试的次数达到了 MAX_SCAN_RETRIES 则改为阻塞锁获取,保证能获取成功。最后解除当前 Segment 的锁

14、CocurrentHashMap(JDK 1.8)

CocurrentHashMap 抛弃了原有的 Segment 分段锁,采用了 CAS + synchronized 来保证并发安全性。其中的 val next 都用了 volatile 修饰,保证了可见性。

最大特点是引入了 CAS

借助 Unsafe 来实现 native code。CAS有3个操作数,内存值 V、旧的预期值 A、要修改的新值 B。当且仅当预期值 A 和内存值 V 相同时,将内存值V修改为 B,否则什么都不做。Unsafe 借助 CPU 指令 cmpxchg 来实现。

CAS 使用实例

对 sizeCtl 的控制都是用 CAS 来实现的:

  • -1 代表 table 正在初始化
  • N 表示有 -N-1 个线程正在进行扩容操作
  • 如果 table 未初始化,表示table需要初始化的大小
  • 如果 table 初始化完成,表示table的容量,默认是table大小的0.75倍,用这个公式算 0.75(n – (n >>> 2))

CAS 会出现的问题:ABA

解决:对变量增加一个版本号,每次修改,版本号加 1,比较的时候比较版本号。

put 过程

  • 根据 key 计算出 hashcode
  • 判断是否需要进行初始化
  • 通过 key 定位出的 Node,如果为空表示当前位置可以写入数据,利用 CAS 尝试写入,失败则自旋保证成功
  • 如果当前位置的 hashcode == MOVED == -1,则需要进行扩容
  • 如果都不满足,则利用 synchronized 锁写入数据
  • 如果数量大于 TREEIFY_THRESHOLD 则要转换为红黑树

get 过程

  • 根据计算出来的 hashcode 寻址,如果就在桶上那么直接返回值
  • 如果是红黑树那就按照树的方式获取值
  • 就不满足那就按照链表的方式遍历获取值

ConcurrentHashMap 在 Java 8 中存在一个 bug 会进入死循环,原因是递归创建 ConcurrentHashMap 对象,但是在 JDK 1.9 已经修复了。场景重现如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public class ConcurrentHashMapDemo{

    private Map<Integer,Integer> cache =new ConcurrentHashMap<>(15);

 

    public static void main(String[]args){

        ConcurrentHashMapDemo ch =    new ConcurrentHashMapDemo();

        System.out.println(ch.fibonaacci(80));       

    }

 

    public int fibonaacci(Integer i){       

        if(i==0||i ==1) {               

            return i;       

        }

 

        return cache.computeIfAbsent(i,(key) -> {

            System.out.println("fibonaacci : "+key);

            return fibonaacci(key -1)+fibonaacci(key - 2);       

        });      

    }

}

HashMap的结构属性:

    public class HashMap<K,V> extends AbstractMap<K,V>
            implements Map<K,V>, Cloneable, Serializable {
        //存储数据的Node数组
        transient Node<K,V>[] table;
        //返回Map中所包含的Map.Entry<K,V>的Set视图。
        transient Set<Map.Entry<K,V>> entrySet;
        //当前存储元素的总个数
        transient int size;
        //HashMap内部结构发生变化的次数,主要用于迭代的快速失败(下面代码有分析此变量的作用)
        transient int modCount;
        //下次扩容的临界值,size>=threshold就会扩容,threshold等于capacity*load factor
        int threshold;
        //装载因子
        final float loadFactor;

        //默认装载因子
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
        //由链表转换成红黑树的阈值TREEIFY_THRESHOLD
        static final int TREEIFY_THRESHOLD = 8;
        //由红黑树的阈值转换链表成UNTREEIFY_THRESHOLD
        static final int UNTREEIFY_THRESHOLD = 6;
        //默认容量(16)
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
         //数组的最大容量 (1073741824)
        static final int MAXIMUM_CAPACITY = 1 << 30;
        //当桶中的bin(链表中的元素)被树化时最小的hash表容量。(如果没有达到这个阈值,即hash表容量小于MIN_TREEIFY_CAPACITY,当桶中bin的数量太多时会执行resize扩容操作)这个MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4倍。
        static final int MIN_TREEIFY_CAPACITY = 64;
        略...

链表的结构

    static class Node<K,V> implements Map.Entry<K,V> {
        //hash
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        略...

红黑二叉树的结构

    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父节点
        TreeNode<K,V> left;       //左节点
        TreeNode<K,V> right;     //右节点
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;

HashMap.put(key, value)插入方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //p:链表节点  n:数组长度   i:链表所在数组中的索引坐标
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //判断tab[]数组是否为空或长度等于0,进行初始化扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //判断tab指定索引位置是否有元素,没有则,直接newNode赋值给tab[i]
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //如果该数组位置存在Node
        else {
            //首先先去查找与待插入键值对key相同的Node,存储在e中,k是那个节点的key
            Node<K,V> e; K k;
            //判断key是否已经存在(hash和key都相等)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果Node是红黑二叉树,则执行树的插入操作
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //否则执行链表的插入操作(说明Hash值碰撞了,把Node加入到链表中)
            else {
                for (int binCount = 0; ; ++binCount) {
                    //如果该节点是尾节点,则进行添加操作
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //判断如果链表长度,如果链表长度大于8则调用treeifyBin方法,判断是扩容还是把链表转换成红黑二叉树
                        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执行p的子节点,开始下一次循环(p = e = p.next)
                    p = e;
                }
            }
            //在循环中判断e是否为null,如果为null则表示加了一个新节点,不是null则表示找到了hash、key都一致的Node。
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //判断是否更新value值。(map提供putIfAbsent方法,如果key存在,不更新value,但是如果value==null任何情况下都更改此值)
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //此方法是空方法,什么都没实现,用户可以根据需要进行覆盖
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //只有插入了新节点才进行++modCount;
        ++modCount;
        //如果size>threshold则开始扩容(每次扩容原来的1倍)
        if (++size > threshold)
            resize();
        //此方法是空方法,什么都没实现,用户可以根据需要进行覆盖
        afterNodeInsertion(evict);
        return null;
    }

1.判断键值对数组tab[i]是否为空或为null,否则执行resize()进行扩容;

2.根据键值key计算hash值得到插入的数组索引i,如果table[i]==null,直接新建节点添加,转向6,如果table[i]不为空,转向3;

3.判断链表(或二叉树)的首个元素是否和key一样,不一样转向④,相同转向6;

4.判断链表(或二叉树)的首节点 是否为treeNode,即是否是红黑树,如果是红黑树,则直接在树中插入键值对,不是则执行5;

5.遍历链表,判断链表长度是否大于8,大于8的话把链表转换为红黑树(还判断数组长度是否小于64,如果小于只是扩容,不进行转换二叉树),在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现key已经存在直接覆盖value即可;如果调用putIfAbsent方法插入,则不更新值(只更新值为null的元素)。

6.插入成功后,判断实际存在的键值对数量size是否超多了最大容量threshold,如果超过,进行扩容。

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

1、首先判断数组的长度是否小于64,如果小于64则进行扩容
2、否则把链表结构转换成红黑二叉树结构

modCount 变量的作用

    public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

从forEach循环中可以发现 modCount 参数的作用。就是在迭代器迭代输出Map中的元素时,不能编辑(增加,删除,修改)Map中的元素。如果在迭代时修改,则抛出ConcurrentModificationException异常。

疑问解答:

1、hash取余数,为什么不用取模操作呢,而用tab[i = (n - 1) & hash]?

它通过 (n - 1) & hash来得到该对象的保存位,而HashMap底层数组的长度总是2的n次方,这是HashMap在速度上的优化。当length总是2的n次方时, (n - 1) & hash运算等价于对length取模,也就是h%length,但是&比%具有更高的效率。

2、为什么使用红黑二叉树呢?

因为在好的算法,也避免不了hash的碰撞,避免不了链表过长的的情况,一旦出现链表过长,则严重影响到HashMap的性能。JDK8对HashMap做了优化,把链表长度超过8个的,则改成红黑二叉树,提高访问的速度。

 

 

Guess you like

Origin blog.csdn.net/w893932747/article/details/90271022