码迷,mamicode.com
首页 > 其他好文 > 详细

ConcurrentHashMap笔记

时间:2017-03-16 19:14:48      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:entry   length   empty   volatile   style   index   指定   int   first   

概览:

   内部存储的数据结构为:数组+链表+红黑树,图示:

   技术分享

重要的属性(内部类):

 

//存放元素的数组
transient volatile Node<K,V>[] table;
//数组中的Node节点
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//Key计算出来的Hash值
        final K key;//Key
        volatile V val;//Value
        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;
        }
        ...//省略
    }
//红黑树中的节点
static final class TreeNode<K,V> extends Node<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;       //左子节点
        TreeNode<K,V> right;    //右子节点
        TreeNode<K,V> prev;    //
        boolean red;
        ...//省略    
    }

//组合TreeNode
static final class TreeBin<K,V> extends Node<K,V> {
        TreeNode<K,V> root;
        volatile TreeNode<K,V> first;
 }

//内部类

 

方法分析

 /** Implementation for put and putIfAbsent */
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();//初始化数组大小,默认16
            //数组指定位置元素为空,直接插入
            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
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {//不为空,链表存储
                V oldVal = null;
                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)))) {
                                    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) {
                            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) {
                    //链表长度大于8,转为红黑树存储
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }
/**
     * Replaces all linked nodes in bin at given index unless table is
     * too small, in which case resizes instead.
     */
    private final void treeifyBin(Node<K,V>[] tab, int index) {
        Node<K,V> b; int n, sc;
        if (tab != null) {
            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
                tryPresize(n << 1);//扩容数组
            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
                synchronized (b) {
                    if (tabAt(tab, index) == b) {
                        TreeNode<K,V> hd = null, tl = null;
              //遍历链表,构造TreeNode
for (Node<K,V> e = b; e != null; e = e.next) { TreeNode<K,V> p = new TreeNode<K,V>(e.hash, e.key, e.val, null, null); if ((p.prev = tl) == null) hd = p; else tl.next = p; tl = p; }
//构建红黑树 setTabAt(tab, index,
new TreeBin<K,V>(hd)); } } } } }

 

 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) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            else if (eh < 0)//红黑树取值
                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; }

 

写在最后:

   为什么使用红黑树? 

      红黑树的特性:

         1、节点是红色或者黑色

         2、根是黑色

         3、所有叶子都是黑色

         4、每个红色节点必须有2个黑色的子节点

         5、从任一节点到其每个叶子的所有简单路径包含相同数目的黑色节点

      根据特性5,从根的最长路径不可能>2倍的最短路径,所以这样的二叉树是平衡的;插入、删除、查询操作比较高效

 

拓展阅读

    1、红黑树介绍    2、深入分析ConcurrentHashMap1.8的扩容实现

 

ConcurrentHashMap笔记

标签:entry   length   empty   volatile   style   index   指定   int   first   

原文地址:http://www.cnblogs.com/Non-Tecnology/p/6560903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!