ConcurrentHashMap的作用与用法

ConcurrentHashMap的作用与用法

一.ConcurrentHashMap简介
ConcurrentHashMap是属于JUC工具包中的并发容器之一,在多线程开发中很经常会使用到这个类,它与HashMap的区别是HashMap是线程不安全的,在高并发的情况下,使用HashMap进行大量变更操作容易出现问题,但是ConcurrentHashMap是线程安全的。
JDK1.8的实现已经抛弃了Segment分段锁机制,利用CAS+Synchronized来保证并发更新的安全,采用的数据结构(数组+链表+红黑树)。
ConcurrentHashMap 是设计为非阻塞的。在更新时会局部锁住某部分数据,但不会把整个表都锁住。同步读取操作则是完全非阻塞的。好处是在保证合理的同步前提下,效率很高。

二.常用方法
1.put方法:
注意put方法上注释:翻译出来:“将指定的键映射到此表中的指定值,键和值都不能为空。”所以ConcurrentHashMap的key和value都不能是null,这是和HashMap有所区别的地方;

	/**
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     */
	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();
        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) //表为空或表长度为0时候
                tab = initTable();
            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)//MOVED=-1;当前正在扩容,一起进行扩容操作
                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) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

2.get操作:
返回指定键映射到的值,或者如果此映射不包含键的映射
1.先判断table是否为空,如果为空,直接返回null。
2.计算key的hash值,并获取指定table中指定位置的Node节点,通过遍历链表或则树结构找到对应的节点,返回value值。

	/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     */
    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode()); // hash算法
        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;
    }

三.ConcurrentHashMap用法展示:实际的使用就很简单了,就理解成集合使用就行

package com.demo.spring.test.baseThread.并发容器;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:  并发容器
 * @Author: yangshilei
 */
public class ConcurrentHashMapDemo implements Runnable{

    private final static ConcurrentHashMap<String,String> map = new ConcurrentHashMap();

    private final static  CountDownLatch latch = new CountDownLatch(100);

    private String key;

    private String value;

    public ConcurrentHashMapDemo(String key,String value){
        this.key = key;
        this.value = value;
    }

    @Override
    public void run() {
        map.put(key,value);
        latch.countDown();
    }


    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(8);
        try {
            for(int i = 1;i<=100;i++){
                ConcurrentHashMapDemo demo = new ConcurrentHashMapDemo("key"+i,"value"+i);
                pool.execute(demo);
            }
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            pool.shutdown();
        }
        System.out.println("map中的属性数量="+map.size());
    }
}

多次运行的结果:

map中的属性数量=100

四.实际项目中使用案例:
在实际的生产环境中,单看代码很多操作并没有使用到我们常说的实现多线程的方式,但是结合具体的使用场景,某个接口或者方法会多次由不同请求发起时候,一个请求就会打开一个新的线程,其场景和直接使用多线程的效果差不多。
由于多线程的情况下,使用hashmap会出现链表闭环,一旦进入了闭环get数据,程序就会进入死循环,因此HashMap是非线程安全的。
所以在这些场景中,我们也要使用ConcurrentHashMap。
1.webSocket用来存放客户端的信息
在这里插入图片描述
2.Redis连接池使用
在这里插入图片描述
3.多线程任务管理
在这里插入图片描述

  • 17
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值