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;}@Overridepublic 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.多线程任务管理