JUC学习之ConcurrentHashMap(JDK1.8)

一、简介

ConcurrentHashMap是线程安全的HashMap,声明如下:

public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable

ConcurrentHashMap相关类图如下:

可见,ConcurrentHashMap继承自AbstractMap,并且实现了ConcurrentMap接口、序列化接口。

其中ConcurrentMap接口又是从Map接口继承过来,如果之前了解过HashMap源码的话,对 Map<K, V>接口应该不会陌生,其中提供了一些针对Map的原子操作。

public interface ConcurrentMap<K, V> extends Map<K, V>

二、常用API

【a】构造方法

ConcurrentHashMap()

用默认的初始表大小(16)创建一个新的空映射

ConcurrentHashMap(int initialCapacity)

创建一个新的空映射,其初始表大小可容纳指定数量的元素,而不需要动态调整大小

ConcurrentHashMap(int initialCapacity, float loadFactor)

扫描二维码关注公众号,回复: 11085126 查看本文章

根据给定初始容量(initialCapacity)和加载因子(loadFactor)创建一个新的空映射,其中包含初始表大小

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

根据给定初始容量(initialCapacity)、加载因子(loadFactor)和并发更新线程数量(concurrencyLevel)创建一个新的空映射

ConcurrentHashMap(Map<? extends K,? extends V> m)

使用与给定映射相同的映射创建新映射

【b】常用方法

方法返回值类型

方法描述

void

clear()

从该映射中删除所有映射

boolean

contains(Object value)

判断一些键是否映射到该表中的指定值

boolean

containsKey(Object key)

判断指定的对象是否是此表中的键

boolean

containsValue(Object value)

如果此映射将一个或多个键映射到指定的值,则返回true

Enumeration<V>

elements()

返回此表中值的枚举

Set<Map.Entry<K,V>>

entrySet()

返回此映射中包含的映射的集合视图

boolean

equals(Object o)

将指定的对象与此映射进行比较以确定是否相等

void

forEach(BiConsumer<? super K,? super V> action)

为映射中的每个条目执行给定的操作,直到处理完所有条目或操作引发异常

V

get(Object key)

返回指定键映射到的值,如果该映射不包含键的映射,则返回null

V

getOrDefault(Object key, V defaultValue)

返回指定键映射到的值,如果该映射不包含键的映射,则返回给定的默认值

int

hashCode()

返回该映射的哈希码值

boolean

isEmpty()

如果此映射不包含键值映射,则返回true

Enumeration<K>

keys()

返回此表中键的枚举

long

mappingCount()

返回映射的数目

V

merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

如果指定的键尚未与(非空)值关联,则将其与给定值关联

V

put(K key, V value)

将指定的键映射到此表中的指定值

void

putAll(Map<? extends K,? extends V> m)

将指定映射的所有映射复制到此映射

V

putIfAbsent(K key, V value)

如果指定的键尚未与某个值关联,请将其与给定的值关联

V

remove(Object key)

从映射中删除键(及其对应的值)

boolean

remove(Object key, Object value)

仅当当前映射到给定值时,删除键的项

V

replace(K key, V value)

如果存在key,则更新为value,返回旧value;否则,返回null

boolean

replace(K key, V oldValue, V newValue)

如果存在key,且值和oldValue一致,则更新为newValue,并返回true;否则,返回false

int

size()

返回此映射中的键值映射的数目

String

toString()

返回此映射的字符串表示形式

Collection<V>

values()

返回此映射中包含的值的集合视图

三、使用示例

下面通过一个示例说明ConcurrentHashMap并发Map的使用:

/**
 * 一个线程对ConcurrentHashMap增加数据,另外一个线程在遍历时就能获得
 */
public class T06_ConcurrentHashMap {
    private static Map<String, String> map = new ConcurrentHashMap<>();

    static {
        for (int i = 0; i < 5; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            String value = "AA";
            map.put("AA", value);
            System.out.println(Thread.currentThread().getName() + "--->put:" + value);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者").start();

        new Thread(() -> {
            for (Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry<String, String> entry = iterator.next();
                System.out.println(Thread.currentThread().getName() + "--->get: " + entry.getKey() + " - " + entry.getValue());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者").start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(Thread.currentThread().getName() + "--->get: " + entry.getKey() + " - " + entry.getValue());
        }

    }
}

运行结果:

生产者--->put:AA
消费者--->get: 0 - 0
消费者--->get: AA - AA
消费者--->get: 1 - 1
消费者--->get: 2 - 2
消费者--->get: 3 - 3
消费者--->get: 4 - 4
main--->get: 0 - 0
main--->get: AA - AA
main--->get: 1 - 1
main--->get: 2 - 2
main--->get: 3 - 3
main--->get: 4 - 4

四、源码阅读

ConcurrentHashMap底层利用CAS + synchronized实现并发更新的安全,底层数据结构是数组 + 链表 + 红黑树来实现的。

ConcurrentHashMap对象的内部结构图大体如下:

ConcurrentHashMap内部存在一个Node[]类型数组:

/**
 * Node[]数组.在第一次插入时懒加载初始化。大小总是二的幂.
 */
transient volatile Node<K,V>[] table;

数组的每一个位置table[i]代表了一个bucket桶,当插入键值对时,会根据键的hash值映射到不同的桶位置,table一共可以包含4种不同类型的桶:

  • Node;
  • TreeBin:TreeBin所链接的是一颗红黑树,红黑树的节点用TreeNode表示;
  • ForwardingNode;
  • ReservationNode;

ConcurrentHashMap一共包含5种节点,我们来看下各个节点的定义和作用:

【a】Node<K,V>节点

当出现hash冲突时,Node节点会以链表的形式链接到table上,当节点数量超过一定数目时,链表会转化为红黑树.

Node<K,V>源码如下:

//实现Map.Entry<K,V>接口
static class Node<K,V> implements Map.Entry<K,V> {
    //hash值
    final int hash;
    //键
    final K key;
    //用volatile修饰,保证并发的可见性
    //值
    volatile V val;
    //链表下一节点
    volatile Node<K,V> next;

    Node(int hash, K key, V val, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.val = val;
        this.next = next;
    }
    
    //获取键
    public final K getKey()       { return key; }
    
    //获取值
    public final V getValue()     { return val; }
    
    //计算哈希码的方式: 将键的哈希码和值的哈希码做异或运算
    public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
    
    public final String toString(){ return key + "=" + val; }
    
    //不支持设置值
    public final V setValue(V value) {
        throw new UnsupportedOperationException();
    }

    //判断相等的方法
    public final boolean equals(Object o) {
        Object k, v, u; Map.Entry<?,?> e;
        return ((o instanceof Map.Entry) &&
                (k = (+.getKey()) != null &&
                (v = e.getValue()) != null &&
                (k == key || k.equals(key)) &&
                (v == (u = val) || v.equals(u)));
    }

    /**
     * 查找方法.
     */
    Node<K,V> find(int h, Object k) {
        Node<K,V> e = this;
        if (k != null) {
            //循环链表进行查找
            do {
                K ek;
                if (e.hash == h &&
                    ((ek = e.key) == k || (ek != null && k.equals(ek))))
                    return e;
            } while ((e = e.next) != null);
        }
        return null;
    }
}

【b】TreeNode<K,V>节点

TreeNode就是红黑树的节点,TreeNode不会直接链接到table[i]—桶上面,而是由TreeBin链接,TreeBin会指向红黑树的根节点.

/**
 * 红黑树节点,在TreeBins中使用的节点
 */
static final class TreeNode<K,V> extends Node<K,V> {
    TreeNode<K,V> parent;  // 红黑树的链接
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // 需要取消链接后删除
    boolean red;

    TreeNode(int hash, K key, V val, Node<K,V> next,
             TreeNode<K,V> parent) {
        super(hash, key, val, next);
        this.parent = parent;
    }

    Node<K,V> find(int h, Object k) {
        return findTreeNode(h, k, null);
    }

    /**
     * 返回给定键从给根节点开始的TreeNode(如果没有找到则为null).
     */
    final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
        if (k != null) {
            //以当前节点(this)为根节点,开始遍历查找指定key
            TreeNode<K,V> p = this;
            do  {
                int ph, dir; K pk; TreeNode<K,V> q;
                TreeNode<K,V> pl = p.left, pr = p.right;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.findTreeNode(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
        }
        return null;
    }
}

【c】TreeBin<K,V>节点

TreeBin直接链接到table[i]—桶上面,该节点提供了一系列红黑树相关的操作,以及加锁、解锁操作。

/**
 * 用于箱子顶部的树节点。TreeBins不保存用户键或值,
 * 而是指向treenode及其根的列表。它们还维护一个读写锁,迫使写操作(持有bin锁的人)等待读操作(不持有的人)在树重组操作之前完成.
 */
static final class TreeBin<K,V> extends Node<K,V> {
    //树的根节点
    TreeNode<K,V> root;
    //链表结构的头结点
    volatile TreeNode<K,V> first;
    //最近的一个设置WAITER标识位的线程
    volatile Thread waiter;
    //锁状态标识
    volatile int lockState;
    // 锁状态的一些值
    static final int WRITER = 1; // 持有写锁时设置
    static final int WAITER = 2; // 等待写锁时设置
    static final int READER = 4; // 设置读锁的增量值

    /**
     * 在hashCode相等并且不是Comparable类型时,用此方法判断大小.
     */
    static int tieBreakOrder(Object a, Object b) {
        int d;
        if (a == null || b == null ||
            (d = a.getClass().getName().
             compareTo(b.getClass().getName())) == 0)
            d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                 -1 : 1);
        return d;
    }

    /**
     * 以b为头节点创建红黑树.
     */
    TreeBin(TreeNode<K,V> b) {
        super(TREEBIN, null, null, null);
        this.first = b;
        TreeNode<K,V> r = null;
        for (TreeNode<K,V> x = b, next; x != null; x = next) {
            next = (TreeNode<K,V>)x.next;
            x.left = x.right = null;
            if (r == null) {
                x.parent = null;
                x.red = false;
                r = x;
            }
            else {
                K k = x.key;
                int h = x.hash;
                Class<?> kc = null;
                for (TreeNode<K,V> p = r;;) {
                    int dir, ph;
                    K pk = p.key;
                    if ((ph = p.hash) > h)
                        dir = -1;
                    else if (ph < h)
                        dir = 1;
                    else if ((kc == null &&
                              (kc = comparableClassFor(k)) == null) ||
                             (dir = compareComparables(kc, k, pk)) == 0)
                        dir = tieBreakOrder(k, pk);
                        TreeNode<K,V> xp = p;
                    if ((p = (dir <= 0) ? p.left : p.right) == null) {
                        x.parent = xp;
                        if (dir <= 0)
                            xp.left = x;
                        else
                            xp.right = x;
                        r = balanceInsertion(r, x);
                        break;
                    }
                }
            }
        }
        this.root = r;
        assert checkInvariants(root);
    }

    /**
     * 获取用于树结构重组的写锁.
     */
    private final void lockRoot() {
        if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
            contendedLock(); // offload to separate method
    }

    /**
     * 释放用于树重组的写锁.
     */
    private final void unlockRoot() {
        lockState = 0;
    }

    /**
     * 可能有等待根锁的块.
     */
    private final void contendedLock() {
        boolean waiting = false;
        for (int s;;) {
            if (((s = lockState) & ~WAITER) == 0) {
                if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
                    if (waiting)
                        waiter = null;
                    return;
                }
            }
            else if ((s & WAITER) == 0) {
                if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
                    waiting = true;
                    waiter = Thread.currentThread();
                }
            }
            else if (waiting)
                LockSupport.park(this);
        }
    }

    /**
     * 返回匹配的节点,如果没有则返回null.
     */
    final Node<K,V> find(int h, Object k) {
        if (k != null) {
            //从跟节点开始查找
            for (Node<K,V> e = first; e != null; ) {
                int s; K ek;
                if (((s = lockState) & (WAITER|WRITER)) != 0) {
                    if (e.hash == h &&
                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
                        return e;
                    e = e.next;
                }
                else if (U.compareAndSwapInt(this, LOCKSTATE, s,
                                             s + READER)) {
                    TreeNode<K,V> r, p;
                    try {
                        p = ((r = root) == null ? null :
                             r.findTreeNode(h, k, null));
                    } finally {
                        Thread w;
                        if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
                            (READER|WAITER) && (w = waiter) != null)
                            LockSupport.unpark(w);
                    }
                    return p;
                }
            }
        }
        return null;
    }

    /**
     * 查找或添加节点
     */
    final TreeNode<K,V> putTreeVal(int h, K k, V v) {
        Class<?> kc = null;
        boolean searched = false;
        for (TreeNode<K,V> p = root;;) {
            int dir, ph; K pk;
            if (p == null) {
                first = root = new TreeNode<K,V>(h, k, v, null, null);
                break;
            }
            else if ((ph = p.hash) > h)
                dir = -1;
            else if (ph < h)
                dir = 1;
            else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
                return p;
            else if ((kc == null &&
                      (kc = comparableClassFor(k)) == null) ||
                     (dir = compareComparables(kc, k, pk)) == 0) {
                if (!searched) {
                    TreeNode<K,V> q, ch;
                    searched = true;
                    if (((ch = p.left) != null &&
                         (q = ch.findTreeNode(h, k, kc)) != null) ||
                        ((ch = p.right) != null &&
                         (q = ch.findTreeNode(h, k, kc)) != null))
                        return q;
                }
                dir = tieBreakOrder(k, pk);
            }

            TreeNode<K,V> xp = p;
            if ((p = (dir <= 0) ? p.left : p.right) == null) {
                TreeNode<K,V> x, f = first;
                first = x = new TreeNode<K,V>(h, k, v, f, xp);
                if (f != null)
                    f.prev = x;
                if (dir <= 0)
                    xp.left = x;
                else
                    xp.right = x;
                if (!xp.red)
                    x.red = true;
                else {
                    lockRoot();
                    try {
                        root = balanceInsertion(root, x);
                    } finally {
                        unlockRoot();
                    }
                }
                break;
            }
        }
        assert checkInvariants(root);
        return null;
    }

    /**
     * 删除指定的节点
     * 1. 红黑树规模太小时,返回true,然后进行 树 -> 链表 的转化;
     * 2. 红黑树规模足够时,不用变换成链表,但删除结点时需要加写锁
     */
    final boolean removeTreeNode(TreeNode<K,V> p) {
        TreeNode<K,V> next = (TreeNode<K,V>)p.next;
        TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
        TreeNode<K,V> r, rl;
        if (pred == null)
            first = next;
        else
            pred.next = next;
        if (next != null)
            next.prev = pred;
        if (first == null) {
            root = null;
            return true;
        }
        if ((r = root) == null || r.right == null || // too small
            (rl = r.left) == null || rl.left == null)
            return true;
        lockRoot();
        try {
            TreeNode<K,V> replacement;
            TreeNode<K,V> pl = p.left;
            TreeNode<K,V> pr = p.right;
            if (pl != null && pr != null) {
                TreeNode<K,V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                    s = sl;
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    TreeNode<K,V> sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                p.left = null;
                if ((p.right = sr) != null)
                    sr.parent = p;
                if ((s.left = pl) != null)
                    pl.parent = s;
                if ((s.parent = pp) == null)
                    r = s;
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                if (sr != null)
                    replacement = sr;
                else
                    replacement = p;
            }
            else if (pl != null)
                replacement = pl;
            else if (pr != null)
                replacement = pr;
            else
                replacement = p;
            if (replacement != p) {
                TreeNode<K,V> pp = replacement.parent = p.parent;
                if (pp == null)
                    r = replacement;
                else if (p == pp.left)
                    pp.left = replacement;
                else
                    pp.right = replacement;
                p.left = p.right = p.parent = null;
            }

            root = (p.red) ? r : balanceDeletion(r, replacement);

            if (p == replacement) {  // detach pointers
                TreeNode<K,V> pp;
                if ((pp = p.parent) != null) {
                    if (p == pp.left)
                        pp.left = null;
                    else if (p == pp.right)
                        pp.right = null;
                    p.parent = null;
                }
            }
        } finally {
            unlockRoot();
        }
        assert checkInvariants(root);
        return false;
    }

    // 红黑树方法
    static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                          TreeNode<K,V> p) {
        TreeNode<K,V> r, pp, rl;
        if (p != null && (r = p.right) != null) {
            if ((rl = p.right = r.left) != null)
                rl.parent = p;
            if ((pp = r.parent = p.parent) == null)
                (root = r).red = false;
            else if (pp.left == p)
                pp.left = r;
            else
                pp.right = r;
            r.left = p;
            p.parent = r;
        }
        return root;
    }

    static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                           TreeNode<K,V> p) {
        TreeNode<K,V> l, pp, lr;
        if (p != null && (l = p.left) != null) {
            if ((lr = p.left = l.right) != null)
                lr.parent = p;
            if ((pp = l.parent = p.parent) == null)
                (root = l).red = false;
            else if (pp.right == p)
                pp.right = l;
            else
                pp.left = l;
            l.right = p;
            p.parent = l;
        }
        return root;
    }

    static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                TreeNode<K,V> x) {
        x.red = true;
        for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
            if ((xp = x.parent) == null) {
                x.red = false;
                return x;
            }
            else if (!xp.red || (xpp = xp.parent) == null)
                return root;
            if (xp == (xppl = xpp.left)) {
                if ((xppr = xpp.right) != null && xppr.red) {
                    xppr.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.right) {
                        root = rotateLeft(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateRight(root, xpp);
                        }
                    }
                }
            }
            else {
                if (xppl != null && xppl.red) {
                    xppl.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.left) {
                        root = rotateRight(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateLeft(root, xpp);
                        }
                    }
                }
            }
        }
    }

    static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                               TreeNode<K,V> x) {
        for (TreeNode<K,V> xp, xpl, xpr;;)  {
            if (x == null || x == root)
                return root;
            else if ((xp = x.parent) == null) {
                x.red = false;
                return x;
            }
            else if (x.red) {
                x.red = false;
                return root;
            }
            else if ((xpl = xp.left) == x) {
                if ((xpr = xp.right) != null && xpr.red) {
                    xpr.red = false;
                    xp.red = true;
                    root = rotateLeft(root, xp);
                    xpr = (xp = x.parent) == null ? null : xp.right;
                }
                if (xpr == null)
                    x = xp;
                else {
                    TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                    if ((sr == null || !sr.red) &&
                        (sl == null || !sl.red)) {
                        xpr.red = true;
                        x = xp;
                    }
                    else {
                        if (sr == null || !sr.red) {
                            if (sl != null)
                                sl.red = false;
                            xpr.red = true;
                            root = rotateRight(root, xpr);
                            xpr = (xp = x.parent) == null ?
                                null : xp.right;
                        }
                        if (xpr != null) {
                            xpr.red = (xp == null) ? false : xp.red;
                            if ((sr = xpr.right) != null)
                                sr.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateLeft(root, xp);
                        }
                        x = root;
                    }
                }
            }
            else { // symmetric
                if (xpl != null && xpl.red) {
                    xpl.red = false;
                    xp.red = true;
                    root = rotateRight(root, xp);
                    xpl = (xp = x.parent) == null ? null : xp.left;
                }
                if (xpl == null)
                    x = xp;
                else {
                    TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                    if ((sl == null || !sl.red) &&
                        (sr == null || !sr.red)) {
                        xpl.red = true;
                        x = xp;
                    }
                    else {
                        if (sl == null || !sl.red) {
                            if (sr != null)
                                sr.red = false;
                            xpl.red = true;
                            root = rotateLeft(root, xpl);
                            xpl = (xp = x.parent) == null ?
                                null : xp.left;
                        }
                        if (xpl != null) {
                            xpl.red = (xp == null) ? false : xp.red;
                            if ((sl = xpl.left) != null)
                                sl.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateRight(root, xp);
                        }
                        x = root;
                    }
                }
            }
        }
    }

    /**
     * 递归检查红黑树的正确性
     */
    static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
        TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
            tb = t.prev, tn = (TreeNode<K,V>)t.next;
        if (tb != null && tb.next != t)
            return false;
        if (tn != null && tn.prev != t)
            return false;
        if (tp != null && t != tp.left && t != tp.right)
            return false;
        if (tl != null && (tl.parent != t || tl.hash > t.hash))
            return false;
        if (tr != null && (tr.parent != t || tr.hash < t.hash))
            return false;
        if (t.red && tl != null && tl.red && tr != null && tr.red)
            return false;
        if (tl != null && !checkInvariants(tl))
            return false;
        if (tr != null && !checkInvariants(tr))
            return false;
        return true;
    }

    private static final sun.misc.Unsafe U;
    private static final long LOCKSTATE;
    static {
        try {
            U = sun.misc.Unsafe.getUnsafe();
            Class<?> k = TreeBin.class;
            LOCKSTATE = U.objectFieldOffset
                (k.getDeclaredField("lockState"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

【d】ForwardingNode节点

ForwardingNode节点:一个特殊的Node节点,hash值为-1,其中存储nextTable的引用。

只有table发生扩容的时候,ForwardingNode才会发挥作用,作为一个占位符放在table中表示当前节点为null或则已经被移动。

/**
 * ForwardingNode是一种临时结点,在扩容进行中才会出现,hash值固定为-1,且不存储实际数据。
 * 如果旧table数组的一个hash桶中全部的结点都迁移到了新table中,则在这个桶中放置一个ForwardingNode。
 * 读操作碰到ForwardingNode时,将操作转发到扩容后的新table数组上去执行;写操作碰见它时,则尝试帮助扩容。
 */
static final class ForwardingNode<K,V> extends Node<K,V> {
    final Node<K,V>[] nextTable;
    ForwardingNode(Node<K,V>[] tab) {
         //hash值为MOVED(-1)的节点就是ForwardingNode
        super(MOVED, null, null, null);
        this.nextTable = tab;
    }
    //访问被迁移到nextTable中的数据
    Node<K,V> find(int h, Object k) {
        // loop to avoid arbitrarily deep recursion on forwarding nodes
        outer: for (Node<K,V>[] tab = nextTable;;) {
            Node<K,V> e; int n;
            if (k == null || tab == null || (n = tab.length) == 0 ||
                (e = tabAt(tab, (n - 1) & h)) == null)
                return null;
            for (;;) {
                int eh; K ek;
                if ((eh = e.hash) == h &&
                    ((ek = e.key) == k || (ek != null && k.equals(ek))))
                    return e;
                if (eh < 0) {
                    if (e instanceof ForwardingNode) {
                        tab = ((ForwardingNode<K,V>)e).nextTable;
                        continue outer;
                    }
                    else
                        return e.find(h, k);
                }
                if ((e = e.next) == null)
                    return null;
            }
        }
    }
}

【e】ReservationNode节点

保留结点,ConcurrentHashMap中的一些特殊方法会专门用到该类结点。

/**
 * 在computeIfAbsent和compute中使用的位置保持节点
 */
static final class ReservationNode<K,V> extends Node<K,V> {
    ReservationNode() {
        super(RESERVED, null, null, null);
    }

    Node<K,V> find(int h, Object k) {
        return null;
    }
}

构造方法:ConcurrentHashMap提供了五个构造器,ConcurrentHashMap,采用了一种“懒加载”的模式,只有到首次插入键值对的时候,才会真正的去初始化table数组。

/**
 * 使用默认的初始表大小创建一个新的空映射(16)
 */
public ConcurrentHashMap() {
}

/**
 * 使用指定初始容量创建ConcurrentHashMap
 */
public ConcurrentHashMap(int initialCapacity) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException();
    //计算大于(initialCapacity + (initialCapacity >>> 1) + 1)最小2次幂的值
    int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
               MAXIMUM_CAPACITY :
               tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
    this.sizeCtl = cap;
}

/**
 * 根据已有的Map构造ConcurrentHashMap
 */
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
    //private static final int DEFAULT_CAPACITY = 16
    //默认容量为16
    this.sizeCtl = DEFAULT_CAPACITY;
    putAll(m);
}

/**
 * 指定table初始容量和负载因子构造ConcurrentHashMap
 */
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
    this(initialCapacity, loadFactor, 1);
}

/**
 * 指定table初始容量、负载因子、并发级别构造ConcurrentHashMap
 */
public ConcurrentHashMap(int initialCapacity,
                         float loadFactor, int concurrencyLevel) {
    if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
        throw new IllegalArgumentException();
        
        //举例子:  initialCapacity=10 loadFactor=0.75  concurrencyLevel=4
        
        //如果指定的初始容量小于并发级别,那么将会扩大初始容量为并发级别一样。
    if (initialCapacity < concurrencyLevel)   // 至少使用相同数量的垃圾桶
        initialCapacity = concurrencyLevel;   // 估计线程
        // 经过下面的计算得出size=14
    long size = (long)(1.0 + (long)initialCapacity / loadFactor);
    //cap计算得到大于14的2次幂,那么就是cap = 2的四次幂 =16
    int cap = (size >= (long)MAXIMUM_CAPACITY) ?
        MAXIMUM_CAPACITY : tableSizeFor((int)size);
        //sizeCtl = 16
    this.sizeCtl = cap;
}

构造方法debug如下图:

重要属性说明:

/**
 * 表的最大容量为2的30次幂
 */
private static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认的初始容量。必须是2的幂(即至少为1),且最大容量为MAXIMUM_CAPACITY .
 */
private static final int DEFAULT_CAPACITY = 16;

/**
 * 最大可能的数组大小(非2的幂次).
 */
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/**
 * 默认并发级别为16,跟默认初始容量一样
 */
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;

/**
 * 负载因子,为了兼容JDK1.8以前的版本而保留。
 * JDK1.8中的ConcurrentHashMap的负载因子恒定为0.75.
 */
private static final float LOAD_FACTOR = 0.75f;

/**
 * 链表转红黑树的阈值,即链接节点数大于8时,链表将转换为红黑树结构.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 红黑树转链表的阈值,即树结点树小于6时,红黑树将转换为链表结构.
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 链表转变成红黑树:并不是达到阈值8,就会发生转换,还会有第二次判断
 * 第二次判断:只有键值对数量大于64,才会发生转换.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

/**
 * 树转变成链表:并不是小于阈值6,就会发生转换,还会有第二次判断
 * 第二次判断:只有键值对数量小于16,才会发生转换.
 */
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;

/**
 * 用于在sizeCtl中记录大小戳的位移位.
 */
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;

/*
 * 节点哈希字段的编码.
 */
static final int MOVED     = -1; // 用于转发节点的散列
static final int TREEBIN   = -2; // 为树根哈希
static final int RESERVED  = -3; // 临时保留节点
static final int HASH_BITS = 0x7fffffff; // 普通节点哈希

/** cpu的数量,对某些大小设限 */
static final int NCPU = Runtime.getRuntime().availableProcessors();

/* ---------------- 属性 -------------- */

/**
 * Node数组。在第一次插入时进行懒加载初始化。大小总是二的倍数.
 */
transient volatile Node<K,V>[] table;

/**
 * 扩容后的新Node数组,仅在扩容时非空.
   默认为null,扩容时新生成的数组,其大小为原数组的两倍
 */
private transient volatile Node<K,V>[] nextTable;

/**
 * 计数初始值
 */
private transient volatile long baseCount;

/**
 * 用于数组初始化和扩容的,当它是负数的时候,表示数组正在进行初始化或扩容.
   -1表示正在初始化
 */
private transient volatile int sizeCtl;

/**
 * 扩容索引,表示已经分配给扩容线程的table数组索引位置。主要用来协调多个线程,并发安全地获取迁移任务(hash桶).
 */
private transient volatile int transferIndex;

/**
 * 自旋标识位,用于CounterCell[]扩容时使用
 */
private transient volatile int cellsBusy;

/**
 * 计数数组,出现并发冲突时使用.
 */
private transient volatile CounterCell[] counterCells;

// 视图相关字段
private transient KeySetView<K,V> keySet;
private transient ValuesView<K,V> values;
private transient EntrySetView<K,V> entrySet;

重要方法分析:

【a】 put(K key, V value): 插入键值对,并且注意键和值都不能为null。

/**
 * 将指定的键映射到此表中的指定值。键和值都不能为空.
 */
public V put(K key, V value) {
    return putVal(key, value, false);
}

final V putVal(K key, V value, boolean onlyIfAbsent) {
    //如果键为空或者值为空,会抛出空指针异常
    if (key == null || value == null) throw new NullPointerException();
    //(key.hashCode() ^ (key.hashCode() >>> 16)) & HASH_BITS
    //(key.hashCode() ^ (key.hashCode() >>> 16)) & 0x7fffffff 进行与运算得到哈希值
    int hash = spread(key.hashCode());
    
    int binCount = 0;
    //自旋插入节点
    //for循环+CAS操作
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        //hash桶为空
        if (tab == null || (n = tab.length) == 0)
            //懒加载机制,真正put值的时候才初始化Node[]数组table
            tab = initTable();
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//table[i]对应的桶为null
            //i = (n - 1) & hash 计算索引 : 【key的hash值 & (table.length-1)】  目的是为了尽可能减少hash冲突
            //CAS设置tab[i],不需要加锁插入链表节点
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;  // 添加到空容器时没有锁
        }
        else if ((fh = f.hash) == MOVED) //MOVED表示是ForwardingNode结点
            //说明此时table正在扩容,则尝试协助数据迁移
            tab = helpTransfer(tab, f);
        else { //hash冲突
            //出现hash冲突,就是桶里面之前已经有了其他节点
            V oldVal = null;
            //hash桶不为空,对tab[i]中的头结点加锁
            //加同步锁,锁住table[i]这个Node节点
            synchronized (f) {
                //再次判断table[i]是否被其他线程修改
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {
                        //binCount 相当于计数器,记录当前位置有几个节点
                        //每遍历一个节点, binCount + 1
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            Node<K,V> pred = e;
                            //尾插法
                            //如果该节点为链表最后一个节点
                            if ((e = e.next) == null) {
                                //创建新的Node节点,插入到链表尾部
                                pred.next = new Node<K,V>(hash, key,
                                                          value, null);
                                break;
                            }
                        }
                    }
                    else if (f instanceof TreeBin) {  //table[i]是红黑树节点
                        Node<K,V> p;
                        binCount = 2;
                        //红黑树插入节点
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }
            if (binCount != 0) {
                if (binCount >= TREEIFY_THRESHOLD)
                    //超过阈值8,发生链表->红黑树转换
                    //相同位置上多个元素是以链表的形式存储的,当链表的长度(元素的个数)超过8时,将其转为树
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    // 计数值加1
    addCount(1L, binCount);
    return null;
}

put方法总结:

注意计算元素在table中下标的方法:

key的哈希值  &   (table.length - 1)

因为table.length 的大小必须为2的幂次,所以(table.length-1)的二进制形式的特点是除最高位外全部是1,可以实现key在table中的均匀分布,能有效减少hash冲突。

如:table.length = 16 table.length - 1 = 15,转换为二进制为:1111.

大致流程是这样的:

  • 如果数组为空,则先初始化数组;
  • 根据key计算哈希值,进而计算应该在数组的什么位置;
  • 取出该位置上的元素,如果为空,则直接构造一个Node,并将元素放置于此;
  • 如果该位置上的元素不为空,则进一步判断是链表还是树(PS:Node还是TreeBin);
  • 如果是Node,则遍历链表,如果发现有key相同的元素,则用新值替换旧值,否则构造Node,并将其插入到链表尾部;
  • 如果是TreeBin,则遍历树,若发现相同key的节点,则用新值替换旧值,否则构造TreeNode,并将其插入到树中;
  • 插入完成以后,最后再看一下要不要转成树型结构;
  • 如果旧值不为空,则返回旧值;

【b】get(Object key):根据key找到对应的值,如果找不到,返回null.

/**
 * 根据key找到对应的值,如果找不到,返回null.
 */
public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    //重新计算哈希值
    int h = spread(key.hashCode());
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (e = tabAt(tab, (n - 1) & h)) != null) {
        if ((eh = e.hash) == h) { // table[i]就是待查找的项,直接返回
            if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                return e.val;
        }
        else if (eh < 0)
            // hash值<0, 说明遇到特殊结点(非链表结点), 调用find方法查找
            return (p = e.find(h, key)) != null ? p.val : null;
            //按链表方式查找
        while ((e = e.next) != null) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

下图为get方法debug图:

get方法总结:首先根据key的哈希值计算映射到table的哪个桶—table[i],主要有三种情况:

  1. 如果table[i]的key和待查找key相同,那直接返回;
  2. 如果table[i]对应的结点是特殊结点(hash值小于0),则通过各种不同节点的find方法查找;
  3. 如果table[i]对应的结点是普通链表结点,则按链表方式查找;

【c】remove(Object key):

/**
 * 从map中删除指定key及其对应的值。如果键不在map中,则此方法不执行任何操作
 */
public V remove(Object key) {
    return replaceNode(key, null, null);
}

/**
  * value: 当 value==null 时 ,删除节点 。否则更新节点的值为value 
 * cv:期望值, 当 map[key].value 等于期望值cv 或者 cv==null的时候 ,删除节点,或者更新节点的值
 */
final V replaceNode(Object key, V value, Object cv) {
    //计算key在桶中的位置
    int hash = spread(key.hashCode());
    //开始自旋循环table
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        //如果table不包含任何元素或者f = table[i]为空,直接循环
        if (tab == null || (n = tab.length) == 0 ||
            (f = tabAt(tab, i = (n - 1) & hash)) == null)
            break;
        else if ((fh = f.hash) == MOVED)   //hash = -1, 说明table正在扩容
            // 协助扩容
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            boolean validated = false;
            //锁住table[i]这个链表头节点
            synchronized (f) {
                //再一次判断table[i]是否等于f,确保没有其他线程修改了table[i]
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {  //链表
                        validated = true;
                        for (Node<K,V> e = f, pred = null;;) {
                            K ek;
                            //找的key对应的node
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                V ev = e.val;
                                    //期望值cv==null: 表示直接更新value/删除节点
                                    //cv不为空,则只有在key的oldValue等于期望值的时候,才更新value/删除节点
                                if (cv == null || cv == ev ||
                                    (ev != null && cv.equals(ev))) {
                                    oldVal = ev;
                                    if (value != null)
                                        //更新value
                                        e.val = value;
                                    else if (pred != null)
                                        // 非链表头节点,直接删除该节点
                                        // 修改next节点指向
                                        pred.next = e.next;
                                    else
                                        // 更新链表头节点
                                        setTabAt(tab, i, e.next);
                                }
                                break;
                            }
                            //当前节点不是目标节点,继续遍历下一个节点
                            pred = e;
                            if ((e = e.next) == null)
                                //到达链表尾部,依旧没有找到,跳出循环
                                break;
                        }
                    }
                    else if (f instanceof TreeBin) {  //红黑树的移除/替换
                        validated = true;
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        TreeNode<K,V> r, p;
                        if ((r = t.root) != null &&
                            (p = r.findTreeNode(hash, key, null)) != null) {
                            V pv = p.val;
                            if (cv == null || cv == pv ||
                                (pv != null && cv.equals(pv))) {
                                oldVal = pv;
                                if (value != null)
                                    p.val = value;
                                else if (t.removeTreeNode(p))
                                    setTabAt(tab, i, untreeify(t.first));
                            }
                        }
                    }
                }
            }
            if (validated) {
                if (oldVal != null) {
                    if (value == null)
                        //如果删除了节点,更新size
                        addCount(-1L, -1);
                    return oldVal;
                }
                break;
            }
        }
    }
    return null;
}

remove()方法debug图如下:

【d】获取table对应的索引元素f的方法tabAt(Node<K,V>[] tab, int i) 

static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }

可见,采用Unsafe.getObjectVolatie()来获取,而不是直接用table[index]的原因跟ConcurrentHashMap的弱一致性有关。在java内存模型中,我们已经知道每个线程都有一个工作内存,里面存储着table的副本,虽然table是volatile修饰的,但不能保证线程每次都拿到table中的最新元素,Unsafe.getObjectVolatile可以直接获取指定内存的数据,保证了每次拿到数据都是最新的。

五、总结

下面总结一下JDK1.8中ConcurrentHashMap与JDK1.7版本的主要区别:

  • 更小的锁粒度:jdk8中摒弃了segment锁(锁分段机制),直接锁定的是hash桶的头结点。JDK1.7中一个segment锁,保护了多个hash桶,而jdk8中一个锁只保护一个hash桶,由于锁的粒度变小了,写操作的并发性也得到更好的提升。
  • 扩容更高效:旧版本最多可以同时扩容的线程数是segment锁的个数。而jdk8中,理论上最多可以同时扩容的线程数是:hash桶的个数(table数组的长度)。但是为了防止扩容线程过多,ConcurrentHashMap规定了扩容线程每次最少迁移16个hash桶,因此jdk8的版本实际上最多可以同时扩容的线程数是:hash桶的个数/16。

简单总结:

  • JDK1.8底层是散列表+红黑树;
  • ConCurrentHashMap支持高并发的访问和更新,线程安全;
  • key和value都不允许为null;

本文主要介绍了ConcurrentHashMap的一些知识,和对常用的API方法如put、remove、get方法的源码进行了总结,JDK8中ConcurrentHashMap源码相对比较复杂,笔者也不能说完全理解透了ConcurrentHashMap中的原理,只能说大概理解,不懂的时候,小伙伴们就Debug一下,一步一步看具体那些变量的值是什么,可能比起纯看好一些。后面如果有时间,肯定还会再去阅读ConcurrentHashMap源码的。下一章我们继续总结一下ConcurrentHashMap中扩容相关的知识。

参考资料:https://www.jianshu.com/p/5bc70d9e5410

发布了250 篇原创文章 · 获赞 112 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/Weixiaohuai/article/details/104761169