并发容器ConcurrentHashMap原理解析

HashMap是线程不安全的,如并发下键相同的put后面的put会覆盖前面的put,这样得到的结果会与实际不符,所以有线程安全的情况下就必须使用一些手段让HashMap变得线程安全,或者用其他线程安全的map替代,而这个安全的map就是Hashtable,但是其效率低下
为什么HashMap线程不安全呢?以put方法为例子,基于jdk1.8

 /**
     * 
     * 将键值对存入map中,如果键处有值就覆盖
     * 
     */
 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }



/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        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 = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

可以看出put方法内部没有任何保证线程安全的措施

为了达到线程安全可以使用Hashtable,我们来看看这个类

在这里插入图片描述
几乎所有的方法都加上了synchronized锁,这样并发度就极其低下,所以一般这个都不会被用

还用一个方法那就是利用Collections工具类,通过包装

Map<String, String> list=Collections.synchronizedMap(new HashMap<String, String>());

这样map也是安全的,看下源码

  public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
        return new SynchronizedMap<>(m);
    }


在这里插入图片描述
底层使用同步代码块的形式保证线程安全,而且使用的是同一个锁对象,这种方式并发度也不高

现在就来看一下主角ConcurrentHashMap,同样是基于jdk’1.8,1.7和1.8在结构上和实现上有很大的区别,
链表加红黑树,1.8采用数组加链表加红黑树的方式,线程安全采取的是synchronized加cas实现,1.7采用采用数组加链表,为了实现线程安全采用的是ReentrantLock加分段锁的方式,这样1.8性能大大得到了提高

看下源码以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) {
    //键值对有一个为null直接抛出异常
        if (key == null || value == null) throw new NullPointerException();
        //计算hash值
        int hash = spread(key.hashCode());
        //数组个数,用来转红黑树
        int binCount = 0;
        //循环数组
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //如果链表为null或者长度为0就初始化
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            //通过cas更新当前key的值
                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 {
            //如果当前key的值为null
                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个而且链表个数超过64个就转换成红黑树
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                    //返回旧值
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        //没有旧值返回null
        return null;
    }

对比1.7的结构,为了线程安全会把整个桶锁住,1.8的方法明显效率更高

组合操作不能保证线程安全

/**
 * 描述:     组合操作并不保证线程安全
 */
public class OptionsNotSafe implements Runnable {
	
    private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<String, Integer>();
   

    public static void main(String[] args) throws InterruptedException {
        scores.put("小明", 0);
        Thread t1 = new Thread(new OptionsNotSafe());
        Thread t2 = new Thread(new OptionsNotSafe());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(scores);
    }


    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
        
                Integer score = scores.get("小明");
                Integer newScore = score + 1;
               scores.put("小明", newScore);
                                    
        }

    }
}

在这里插入图片描述
结果实际数值比正常少很多。

所以针对这种组合操作ConcurrentHashMap也提供了一些方法,专门用来处理组合操作比如:replace()方法
修改上面代码:

  for (int i = 0; i < 1000; i++) {
  //自旋
            while (true) {
                Integer score = scores.get("小明");
                Integer newScore = score + 1;
                //cas,不断判断,第一个参数是key,第二个参数是期望值,第三个是更新值
                //当实际值和期望值是一样的用新值更新旧的值并返回true否则返回false
                boolean b = scores.replace("小明", score, newScore);
                if (b) {
                //退出循环
                    break;
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值