Map集合--线程安全的ConcurrentHashMap(JDK1.8)

一、默认值

    private static final int MAXIMUM_CAPACITY = 1 << 30;//与HashMap 一样


    private static final int DEFAULT_CAPACITY = 16;//与HashMap 一样

    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//


    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;//为了兼容1.7版本,并没有使用


    private static final float LOAD_FACTOR = 0.75f;//与HashMap一样

    static final int TREEIFY_THRESHOLD = 8;//与HashMap一样

    static final int UNTREEIFY_THRESHOLD = 6;//与HashMap一样

    static final int MIN_TREEIFY_CAPACITY = 64;//与HashMap一样


    private static final int MIN_TRANSFER_STRIDE = 16;//??


    private static int RESIZE_STAMP_BITS = 16;//??

    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;//??

    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;//??

    static final int MOVED     = -1; // forwarding nodes的hash值
    static final int TREEBIN   = -2; // tree root 的hash值
    static final int RESERVED  = -3; // hash for transient reservations
    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
    transient volatile Node<K,V>[] table;

    /**
     * The next table to use; non-null only while resizing.
     */
    private transient volatile Node<K,V>[] nextTable;

    /**
     * Base counter value, used mainly when there is no contention,
     * but also as a fallback during table initialization
     * races. Updated via CAS.
     */
    private transient volatile long baseCount;

    /**
     * Table initialization and resizing control.  When negative, the
     * table is being initialized or resized: -1 for initialization,
     * else -(1 + the number of active resizing threads).  Otherwise,
     * when table is null, holds the initial table size to use upon
     * creation, or 0 for default. After initialization, holds the
     * next element count value upon which to resize the table.
     */
     /**
      * 用于Map初始化和扩容操作,-1表示Map初始化
      * —N表示有N-1个线程在执行扩容操作
      * 如果table是null的,那么这个值就是由构造方法执行时确定的
      */
    private transient volatile int sizeCtl;

    private transient volatile int transferIndex;

    private transient volatile int cellsBusy;


    private transient volatile CounterCell[] counterCells;

构造方法

总共有五个构造方法,其中只需要注意其中的三个就可以了

    public ConcurrentHashMap() {
    }

    public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));//将初始化initialCapacity设置为2的次幂
        this.sizeCtl = cap;
    }

    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
        this(initialCapacity, loadFactor, 1);
    }

    //为了向后兼容JDK1.7版本中而是用的一个构造方法,可以忽略
    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }

ConcurrentHashMap的put方法

put方法
    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    /** Implementation for put and putIfAbsent */
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        //计算key的hash值
        int hash = spread(key.hashCode());
        int binCount = 0;
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //1、如果tab第一次使用,则进行初始化
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //2、定位key在tab中的位置,如果tab[index]没有值,那么直接添加,否则进入下一个步骤
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //3、表示当前
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);

            else {
                V oldVal = null;
                //4、锁住table[index]的头结点这个对象,其他的线程还是可以操作其他的bin的
                synchronized (f) {
                    if (tabAt(tab, i) == f) {//如果头结点是链表
                        if (fh >= 0) {
                            binCount = 1;
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {//如果bin中已存在key那么替换原来的value
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {//如果链表中不存在那么就直接添加在尾节点
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        else if (f instanceof TreeBin) {//如果头结点是Black-Red-Tree
                            Node<K,V> p;
                            binCount = 2;
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {//如果添加不成功,那么表示TreeBin中已存在相同的Key,直接替换
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {//如果binCount超过了TREEIFY_THRESHOLD,那么就将tab[i]的结构由List->Tree。和HashMap中一样
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

所以put方法大致流程总结如下:

步骤描述
步骤一使用ConcurrentHashMap的spread方法区计算key的hash值
步骤二定位key在tab中的位置,如果tab[index]没有值,那么直接添加,否则进入下一个步骤
步骤三
步骤四锁住table[index]的头结点这个对象,等价于锁定了整个bin;但是其他的线程还是可以操作其他的bin的
步骤五如果头结点是链表则遍历链表,在遍历链表的时候如果链表中存在已有的Key,那么就替换当前的value;如果没有,那么将当前的新建一个Node包含key-value添加到链表的尾部
步骤六如果头结点是TreeBin,那么表示这个bin的数据结构是一个Black-Red Tree,调用putTreeVal()方法将key-value插入到Tree中,如果插入成功,返回一个null;如果插入不成功,表示TreeBin中有相同的key,那么此时会返回那个TreeNode,这时我们只需替换val值就可以了
步骤七如果我们的Bin中Entry的数量大于TREEIFY_THRESHOLD,那么我们就要考虑是否将Bin的数据结构由List->Tree了,这个时候如果我们的bin的数量(tab.length)小于MIN_TREEIFY_CAPACITY,那么我们就只是扩容;反之我们需要转换一下数据结构
initialTable()方法
    private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    if ((tab = table) == null || tab.length == 0) {
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

参考文章

https://blog.csdn.net/u010412719/article/details/52145145

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值