线程安全集合类概述
线程安全集合类可以分为三大类:
-
遗留的线程安全集合如Hashtable,Vector
-
使用Collections装饰的线程安全集合,如:
- Collections.synchronizedCollection
- Collections.synchronizedList
- Collections.synchronizedMap
- Collections.synchronizedSet
- Collections.synchronizedNavigableMap
- Collections.synchronizedNavigableSet
- Collections.synchronizedSortedMap
- Collections.synchronizedSortedSet
-
java.util.concurrent.*
重点介绍java.util.concurrent.*下的线程安全集合类,可以发现它们有规律,里面包含三类关键词:Blocking 、CopyOnWrite、Concurrent
-
Blocking 大部分实现基于锁,并提供用来阻塞的方法
-
CopyOnWrite之类容器修改开销相对较重
-
Concurrent类型的容器
-
内部很多操作使用cas优化,一般可以提供较高吞吐量
-
弱一致性
- 遍历时弱一致性,例如,当利用迭代器遍历时,如果容器发生修改,迭代器仍然可以进行遍历,这时内容是旧的
- 求大小弱一致性,size操作未必是100%
- 读取弱一致性
遍历时如果发生了修改,对于非线程安全来讲,使用fail-fast机制也就是让遍历立刻失败,抛出ConcurrentModificationException,不再继续遍历
重要属性和内部类
/**
* 默认为0
* 当初始化时,为 -1
* 当扩容时,为 -(1 + 扩容线程数)
* 当初始化或扩容完成后,为下一次的扩容的阈值大小
*/
private transient volatile int sizeCtl;
// 整个 ConcurrentHashMap 就是一个Node[]
static class Node<K,V> implements Map.Entry<K,V> {}
// hash 表
transient volatile Node<K,V> [] table;
// 扩容时的 新 hash 表
private transient volatile Node<K,V> [] nextTable;
// 扩容时如果某个 bin 迁移完毕, 用ForwardingNode 作为旧 table bin 的头结点
static final class ForwardingNode<K,V> extends Node<K,V> {}
// 用在 compute 以及 computeIfAbsent时,用来占位,计算完成后替换为普通 Node
static final class ReservationNode<K,V> extends Node<K,V> {}
// 作为treebin 的头结点,存储root 和 first
static final class TreeBin<K,V> extends Node<K,V> {}
// 作为 treebin 的节点,存储parent,left,right
static final class TreeNode<K,V> extends Node<K,V> {}
重要方法
// 获取 Node[] 中第 i 个Node
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab,int i);
// cas 修改 Node[] 中第 i 个Node 的值,c 为旧值 ,v 为新值
static final <k,v> boolean casTabAt(Node<K,V> [] tab,int i,Node<k,v> c,Node<k,v> v);
// 直接修改Node[] 中第 i个 Node 的值,v为新值
static final <K,V> void setTabAt(Node<K,V> [] tab ,int i,Node<K,V> v)