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



