# 并发容器篇

前方核能

最近没怎么碰代码,想到后几天要一面阿里,就跑来写这个了,盲猜面试必问

先上问题:

1.谈一谈HashMap的实现原理

2.线程安全问题以及解决办法

3.并发容器都有哪些?

4.HashMap、ConcurrentHashMap源码。HashMap是线程安全的吗?Hashtable呢? 1.7、1.8实现有何不同?

前置知识以及操作环境

Synchronized以及ReentrantLock

jdk1.8

# ConcurrentHashMap与HashMap

众所周知,像Map这种{Key,Value}的结构非常经典,常用于内存中存放数据。Redis就是高性能Key-value库。在查询中时间复杂度为O(1)

JSON传输数据也是Key-value

首先需要介绍一下HashMap

# HashMap在JDK1.8的前前后后

JDK1.8之前HashMap由链表+数组组成。

jdk1.7HashMapInternal

JDK1.8之后HashMap的组成多了红黑树,在满足下面两个条件之后,会执行链表转红黑树操作,以此来加快搜索速度 。

  • 链表长度大于阈值(默认为 8)&&
  • HashMap 数组长度超过 64

HashMap

# 存储过程

HashMap 通过 key 的 hashCode 经过扰动函数(HashMap的hash方法,防止一些较差的hashCode方法,减少碰撞)处理过后得到 hash 值,然后通过 (n - 1) & hash 判断当前元素存放的位置(这里的 n 指的是数组的长度),如果当前位置存在元素的话,就判断该元素与要存入的元素的 hash 值以及 key 是否相同,如果相同的话,直接覆盖,不相同就通过拉链法(数组中每一个位置都是一个链表,遇到哈希冲突时,将冲突值加到链表中即可)解决冲突。

在研究之前,我们先把类中的属性明确一下。

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    //序列号,显示声明serialVersionUID可以避免对象不一致
    private static final long serialVersionUID = 362498820763181265L;
    // 默认的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    // 最大容量,2^30
    static final int MAXIMUM_CAPACITY = 1 << 30;
    // 默认的负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8;
    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 存储元素的数组,总是2的幂次倍
    transient Node<k,v>[] table;
    // 存放具体元素的集
    transient Set<map.entry<k,v>> entrySet;
    // 存放元素的个数,注意这个不等于数组的长度。
    transient int size;
    // 每次扩容和更改map结构的计数器
    transient int modCount;
    // 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
    int threshold;
    // 加载因子
    final float loadFactor;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

重点关注几个参数:

DEFAULT_LOAD_FACTOR负载因子

loadFactor 加载因子是控制数组存放数据的疏密程度,loadFactor 越趋近于 1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加,loadFactor 越小,也就是趋近于 0,数组中存放的数据(entry)也就越少,也就越稀疏 。

给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。

AlibabaJava规约中就将其初始化作为一项检查,能预估好HashMap大小最好,能尽量减少扩容带来的性能消耗。

TREEIFY_THRESHOLD转换为树的临界值

为什么是8呢?官方注释中前面写了这么一个依据

HashMap-Treeify_Threshod

讲了个啥呢?因为树节点TreeNodeextend LinkedHashMap.Entry<K,V>的空间时正常节点Nodeimplements Map.Entry<K,V>空间的两倍,只有容器包含足够的节点以保证使用时才使用它们,一般树容器很少被使用,随机哈希码下容器中的节点遵循泊松分布,通过泊松分布实验预估,预期列表大小k的出现次数为(exp(-0.5)*pow(0.5,k)/ k! )当k>=8时出现概率仅为0.00000006,所以将转红黑树的因子设置为8。

# 两者区别

hash函数

JDK1.7
static int hash(int h) {
    // 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);
}
1
2
3
4
5
6
JDK1.8
static int hash(int h) {
    // 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);
}
1
2
3
4
5
6

通过对比代码可以看到JDK1.7在性能上会有损失,因为扰动了四次。

哈希冲突

通过JDK1.7中的数据结构,我们已经可以假象一个场景,如果每次hash都不幸命中同一个数组位置,那么查询效用将会变成O(n)。

因此在JDK1.8之后

当链表长度大于阈值(默认为 8)时,会首先调用 treeifyBin()方法。这个方法会根据 HashMap 数组来决定是否转换为红黑树。只有当数组长度大于或者等于 64 的情况下,才会执行转换红黑树操作,以减少搜索时间。否则,就是只是执行 resize() 方法对数组扩容。相关源码这里就不贴了,重点关注 treeifyBin()方法即可!

treeifyBin
/**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# HashMap源码分析

# Node与TreeNode

Node结构
    static class Node<K,V> implements Map.Entry<K,V> {
        //hash值
        final int hash;
        //写入时的键
        final K key;
        //写入时的值
        V value;
        //指向下一链表节点的值
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
TreeNode结构
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links 父
        TreeNode<K,V> left;    //左
        TreeNode<K,V> right;   //右
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;           // 判断颜色
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node. 返回根
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 构造函数

构造函数源码
/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity  给定初始容量
     * @param  loadFactor      the load factor  指定加载因子
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.初始化容量
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     * 默认构造函数,初始容量为16,加载因子为0.75
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     * 将一个普通Map转化为HashMap
     * @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);//这个方法罗列在下面
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
putMapEntries()
/**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map Map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).evict(驱逐,赶出)这个变量当在map构造器传入指定      * map初始化的时候是false,其他情况为true,也即其他构造器创建map之后再调用put方法,该参数则为true
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            // 判断table是否已经初始化
            if (table == null) { // pre-size
                // 未初始化,s为m的实际元素个数
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                // 计算得到的t大于阈值,则初始化阈值,问题:为什么能将threshold直接赋值?而不是tableSizeFor(t)*loadFactor;那么我用的时候岂不是要直接扩容了!答:在构造方法中,并没有对table这个成员变量进行初始化,table的初始化被推迟到了put方法中,在put方法中会对threshold重新计算
                if (t > threshold)
                    threshold = tableSizeFor(t);//下面模拟一下tableSizeFor()
            }
            // 已初始化,并且m元素个数大于阈值,进行扩容处理
            else if (s > threshold)
                resize();
            // 将m中的所有元素添加至HashMap中
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);//putVal为内部方法,是put调用的方法,用户仅可调用put.
            }
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
模拟tableSizeFor()
/**
     * Returns a power of two size for the given target capacity.
     * 解决的问题:取一个整数大于等于它,并且是2的整数次幂的最小数
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final int tableSizeFor(int cap) {
        int n = cap - 1; //防止32这样2的n次幂数被放大为两倍
        n |= n >>> 1; //右移一位
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    public static void main(String[] args) {
        System.out.println(MAXIMUM_CAPACITY);
        int cap = 20;
        learnTableSizeFor(cap);
        int cap2 = 32;
        learnTableSizeFor(cap2);
        int cap3 = 1 << 31;
        learnTableSizeFor(cap3);
    }

     static void learnTableSizeFor(int cap){
         int n = cap - 1;
         System.out.println(n);
         n |= n >>> 1;
         System.out.println(n);
         n |= n >>> 2;
         System.out.println(n);
         n |= n >>> 4;
         System.out.println(n);
         n |= n >>> 8;
         System.out.println(n);
         n |= n >>> 16;
         System.out.println(n);
         System.out.println((n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1);
         System.out.println();
     }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
1073741824
19
27
31
31
31
31
32

31
31
31
31
31
31
32

2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
1073741824
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# put方法

/**
     * 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 key, or
     *         null if there was no mapping for key.
     *         (A null return can also indicate that the map
     *         previously associated null with key.)null也可以是key
     */    
     public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);//实际调用本方法中的putVal
    }
/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key key的哈希值(hash(key))
     * @param key the key Key值
     * @param value the value to put Value值
     * @param onlyIfAbsent if true, don't change existing value 如果为true,则不更改现有值
     * @param evict if false, the table is in creation mode.如果为false,则表处于创建模式。
     * @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;
        //table是否为空或者长度为0
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;//是则resize扩容
        //根据hash计算数组下标并赋值给p,对应位置是否为null
        if ((p = tab[i = (n - 1) & hash]) == null)
            //对应位置为null,直接插入这个<key,value>
            tab[i] = newNode(hash, key, value, null);
        else {
            //对应位置不为null
            Node<K,V> e; K k;
            //判断该位置的hash值与传入hash值是否相等,key是否存在
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;// 将第一个元素赋值给e,用e来记录
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//不存在则判断是否为树节点
            else {
                //两者兼不是,则说明要以链表插入
                for (int binCount = 0; ; ++binCount) {
                    //开始遍历链表,p.next是否为null
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);//是,直接插入新节点
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st判断链表遍历的次数是否大于变红黑树阈值
                            treeifyBin(tab, hash);//是则将链表变树,只有当数组长度大于或者等于 64 的情况下,才会执行转换红黑树操作,以减少搜索时间。否则,就是只是对数组扩容。
                        break;
                    }
                    //判断该位置的hash值与传入hash值是否相等,key是否存在
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;//结束遍历
                    p = e;//将此节点记住,用于遍历链表与34行相互使用
                }
            }
            // 在桶中找到key值、hash值与插入元素相等的结点
            if (e != null) { // existing mapping for key
                // 记录e的value
                V oldValue = e.value;
                // onlyIfAbsent为false或者旧值为null
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//用新值替换旧值
                // 访问后回调,保证链表有序性
                afterNodeAccess(e);
                // 返回旧值
                return oldValue;
            }
        }
        // 结构性修改
        ++modCount;
        // 实际大小大于阈值则扩容
        if (++size > threshold)
            resize();
        // 插入后回调,可以在这复写逻辑
        afterNodeInsertion(evict);
        return null;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

对于 JDK1.8put 方法的分析如下:

  • 如果定位到的数组位置没有元素 就直接插入。
  • 如果定位到的数组位置有元素,遍历以这个元素为头结点的链表,依次和插入的 key 比较,如果 key 相同就直接覆盖,不同就采用头插法插入元素。

# get方法

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

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) {
            // 在树中get
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 在链表中get
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# resize方法

进行扩容,会伴随着一次重新 hash 分配,并且会遍历 hash 表中所有的元素,是非常耗时的。在编写程序中,要尽量避免 resize。

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;
        }
        // 没超过最大值,就扩充为原来的2倍
        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
        newCap = oldThr;
    else {
        // signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 计算新的resize上限
    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) {
        // 把每个bucket都移动到新的buckets中
        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 {
                    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);
                    // 原索引放到bucket里
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 原索引+oldCap放到bucket里
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

# ConcurrentHashMap的出现以及解决的问题

在实际生产环境中,HashMap中的put()与resize()会出现线程不安全的问题。主要在于线程之间的不可见。

# put不安全

场景一:两个线程同时对一个HashMap进行读写,于是当写线程改变的部分还没有被同步到读线程中,读线程就会读取到本地内存修改前的数据。

场景二:三个线程A,B,C,其中A,B两个同时进行修改,A线程先改了,然后轮到C的时间,C将数据同步进来,于是就读到了A的数据。此时可能数据还正确,但可能不幸的是,B线程也进来,并且携带着一个key与A相同,但value不同的值。CPU调度了C读,由于B带有的值C线程根本不知道,于是悲剧就出现了。

针对put函数写一个测试用例(实际只需要写一个多线程就ok)

put不安全示例
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class HashMapLearn1 {
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static HashMap<Object, Object> hashMap = new HashMap<>(16);

    public static void main(String[] args) {
        MapPutRunner mapPutRunner = new MapPutRunner();
        MapGetRuuner mapGetRuuner = new MapGetRuuner();
        Thread m1 = new Thread(mapPutRunner, "m1");
        Thread m2 = new Thread(mapPutRunner, "m2");
        Thread m3 = new Thread(mapGetRuuner, "m3");
        m1.start();
        m2.start();
        m3.start();
    }

    static class MapPutRunner implements Runnable {
        @Override
        public void run() {
            for (; ; ) {
                int random = (int) (Math.random() * 100);
                hashMap.put("index", random);
                System.out.println("放入时是:" + random);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    static class MapGetRuuner implements Runnable {
        @Override
        public void run() {
            for (; ; ) {
                double random = (int) (Math.random() * 100);
                Object index = hashMap.get("index");
                System.out.println("取出时是:" + index);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
放入时是:0
取出时是:0
放入时是:1
取出时是:0 #并发错误
放入时是:2
取出时是:2
取出时是:3
放入时是:3
1
2
3
4
5
6
7
8

针对resize函数写一个测试用例,思路就是并发场景下进行扩容,如果size不能够达到预期,则说明并发中产生问题。

resize不安全示例

# 参考:

https://blog.csdn.net/weixin_44460333/article/details/86770169 (opens new window)

https://snailclimb.gitee.io/javaguide/#/docs/java/collection/HashMap(JDK1.8)源码+底层数据结构分析?id=hashmap-简介 (opens new window)