并发容器-1
并发容器概览
- ConcurrentHashMap:线程安全的HashMap。
- CopyOnWriteArrayList:线程安全的List。
- BlockingQueue:这是一个接口,表示阻塞队列,非常适合用于作为数据共享的通道。
- ConcurrentLinkedQueue:高效的非阻塞并发队列,使用链表实现。可以看做一个线程安全的LinkedList。
- ConcurrentSkipListMap:是一个Map,使用跳表的数据结构进行快速查找。
- 等
父辈同步容器
Vector
可以从源码看到,基本上方法都被synchronized修饰了,所以性能较差。
public synchronized E get(int index)
public synchronized <T> T[] toArray(T[] a)
public synchronized E set(int index, E element)
public synchronized boolean add(E e)
Hashtable
可以看到实现原理和vector相同都是使用大量的synchronized修饰方法。
public synchronized V get(Object key)
public synchronized V put(K key, V value)
public synchronized V remove(Object key)
Collections安全化HashMap和ArrayList
Collections.synchronizedList(new ArrayList())和Collections.synchronizedMap(new HashMap<K, V>))
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<>(list) :
new SynchronizedList<>(list));
}
在SynchronizedRandomAccessList的父类中我们可以找到实现方法。
基本上也就是在方法上套锁,虽然套的是代码块,但代码块里调用了方法。
public E get(int index) {
synchronized (mutex) {return list.get(index);}
}
public E set(int index, E element) {
synchronized (mutex) {return list.set(index, element);}
}
public void add(int index, E element) {
synchronized (mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized (mutex) {return list.remove(index);}
}
绝大多数并发情况下,ConcurrentHashMap和CopyOnWriteArrayList的性能都更好。
如果一个list经常修改,那么CopyOnWriteArrayList性能就大大下降,因为会不停复制,不如前辈了。
ConcurrentHashMap(重点)
Map
SortedMap接口继承了Map接口,key需要是不可变的。
- HashMap:key只能有一个null
- Hashtable:键值对两个都不能有null,所有方法都是同一把锁。
- LinkedHashMap:有序的,需要插入顺序的时候使用。
- TreeMap:实现了SortedMap,使用红黑树排序。
回顾Map接口:
Map<String,Integer> map = new HashMap<>();
map.isEmpty();
map.put("a",1);
map.keySet();
map.get("a");
map.size();
HashMap
JDK1.8是在拉链法解决Hash冲突的基础上加入了红黑树,加快查询,同时通过平衡防止树退化成链表。
红黑树(了解,原因:联想到了ml的过拟合,泛化能力较弱)
红黑树的约束:
- 每个结点不是红色就是黑色。
- 根结点都是黑色root。
- 叶子节点(特指空节点)是黑色的:出度为0,满足了性质就可以近似的平衡了。
- 每个红色节点的子节点都是黑色的。
- 任何一个节点到其每一个叶子节点的所有路径上黑色节点数相同
红黑树的特点:
速度特别快,趋近平衡树,查找叶子元素最少和最多次数不多于二倍
HashMap关于并发的特点
- 非线程安全。
- 迭代时不允许修改内容,会有并发修改异常。
- 只读的并发是安全的。
- 如果一定要把HashMap用在并发环境,用Collections.synchronizedMap(new HashMap())。
为什么需要ConcurrentHashMap
为什么不用Collections.synchronizedMap() 和Hashtable?
性能差劲,锁又沉又大。
为什么HashMap线程不安全?
-
同时put碰撞导致数据丢失
如果两个线程放同一个位置,那么有一个数据就会被挤掉而不被发现。 -
同时put扩容导致数据丢失
如果发现同时需要扩容,如果rehash有和新值相同的key也会只留下一个数据。 -
多线程时死循环造成的CPU100%(JDK7及以前)(了解)
扩容的时候会造成链表的死循环,infinite loop,原因是头插法以及头取。
JDK7的ConcurrentHashMap
- 多个分段锁(默认是16个Segment)包裹一个个hashmap,每段map仍然是可扩容数组和链表组成的。
- 每个segment都有自己的ReentrantLock锁,提高了并发效率。
- ConcurrentHashMap 默认有16个Segments,所以最多可以同时支持16个线程并发写。这个默认值可以在初始化的时候设置为其他值,但是一旦初始化以后,是不可以扩容的。
Segment
static final class Segment<K,V> extends ReentrantLock implements Serializable {}
JDK8的ConcurrentHashMap源码
代码量为之前的六倍,差距也很大。
不再使用Segment而是Node,而且保证并发采用的是CAS加上synchronized。
结构几乎和HashMap一样
put
根据对应位置节点的类型,来赋值,或者helpTransfer,或者增长链表,或者给红黑树增加节点。
final V putVal(K key, V value, boolean onlyIfAbsent) {
//这里先置条件和Hashtable相同
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;
//长度为0就初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//位置是空的,使用Unsafe的CAS操作直接放入
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
}
//当前hash值是否等于MOVED,即当前位置正在扩容
else if ((fh = f.hash) == MOVED)
//Helps transfer if a resize is in progress.
tab = helpTransfer(tab, f);
//有值则进入else
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;
//根据hash找到位置,没有对应的key则跳过本if
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;
}
get
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
//得到hash值
int h = spread(key.hashCode());
//先判断如果表不为空,表长度大于0,e的地方不为空,才去获取,否则直接返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
//当前key匹配,就返回值
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
//如果ehash小于0说明是红黑树节点或者是转移节点
else if (eh < 0)
//使用find,这里使用了多态的方式。
//TreeNode继承了Node,实际调用的就是findTreeNode方法。
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.7的结构改成1.8的结构?
-
并发度由原来的默认16变成了每个节点。在putVal中看到
synchronized (f)
,f是根据hash值取出的first节点。 -
Hash碰撞解决方法与HashMap一同由拉链法变成拉链法加升级红黑树。
-
JDK7是Segment继承的ReentrantLock,而JDK8是CAS加上synchronized。
-
查询复杂度,在外挂数据较多的时候,即红黑树对链表的一个优势O(logN)和O(N)。
-
为什么超过8转红黑树。空间上红黑树比较大,所以在时间和空间上进行了折中。一般来说是不会转红黑树的,如果Hash函数比较完美,那么树化的几率只有0.00000006。
可以看另一篇专门记录HashMap数据结构的笔记
hashmap
组合操作导致的安全问题?
主要看run方法中,get和put是线程安全的,但是中间有个非安全的操作,导致了安全间隙。
例如:两个线程取到10,都加上1再put回去,那就是11了。对比a++操作:分为取值,加一,存储,也是同样的原因。
public class ConcurrentHashMapNotSafe implements Runnable{
//你以为的线程不安全,其实并不是
private static ConcurrentHashMap<String,Integer> age = new ConcurrentHashMap<>();
public static void main(String[] args) {
age.put("迪丽热妈",17);
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
executor.submit(new ConcurrentHashMapNotSafe());
}
executor.shutdown();
while (!executor.isTerminated()){
}
System.out.println(age);
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
Integer age= age.get("迪丽热妈");
age+=1;
age.put("迪丽热妈",age);
}
}
}
解决办法
-
对类似a++的操作进行synchronized的保护,但是
-
public boolean replace(K key, V oldValue, V newValue)
原理
两个replace方法调用的都是这个方法,里面通过synchronized(f)也就是头节点上锁替换处的代码块,结构和put方法有点像。
final V replaceNode(Object key, V value, Object cv)
改正
//通过replace的返回值来确定更改是否成功。有CAS那味 for (int i = 0; i < 1000; i++) { boolean flag=false; while (true){ Integer score = scores.get("小明"); //复杂的运算可以提取出来。 flag=scores.replace("小明",score,score+1); if (flag) break; } }
其他组合操作方法
-
replace 如上
-
putIfAbsent(absent:缺席,不存在,缺少)取不到就put,有值就取出
if (!map.containsKey(key)){ return map.put(key,value); }else{ return map.get(key); }
实际生产案例分享
来自悟空老师
线上考试,需要乱序,直接在内存中做,而且使用了线程不安全的guava的一个map作为缓存,当多个请求进来,并且同时执行乱序的时候,就出现安全问题了。出现了题目重复的问题。
那么就可以使用ConcurrentHashMap。