public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
/* ---------------- Constants -------------- */
/**
* table 的最大长度。这个值必须恰好是1<<30,才能保持在Java数组分配和索引范围内
* table的大小为2的幂,而且还需要这样做,因为32位哈希字段的前两位用于控制目的。
* The largest possible table capacity. This value must be
* exactly 1<<30 to stay within Java array allocation and indexing
* bounds for power of two table sizes, and is further required
* because the top two bits of 32bit hash fields are used for
* control purposes.
*/
// int 的最大值是 1 << 31 -1, 而table的长度必须是2 的幂,所以最大值只能是 1 << 30
// 32位哈希字段的前两位用于控制目的?
// -> 当 table的长度由 1 << 29 (第30位是1) 扩容到 1 << 30时, 判断的是hash值的第30位的值,
// 扩容到 1 << 30后,不会再进行扩容,因此,hash值的第31 和 32位对元素在table中的分布永远不会有
// 任何的影响,因此最适合用于控制目的
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* table 的默认初始容量。必须是2的幂(即,至少1)和最大 MAXIMUM_CAPACITY。
* The default initial table capacity. Must be a power of 2
* (i.e., at least 1) and at most MAXIMUM_CAPACITY.
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* 数组的最大长度。
* The largest possible (non-power of two) array size.
* Needed by toArray and related methods.
*/
// 一些vm在数组中保留一些头信息。试图分配更大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* table 的默认并发级别。未使用,但为与该类以前的版本兼容而定义。
* The default concurrency level for this table. Unused but
* defined for compatibility with previous versions of this class.
*/
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
* table 的负载因子。在构造函数中重写此值只会影响初始表容量。
* The load factor for this table. Overrides of this value in
* constructors affect only the initial table capacity.
* 通常不使用实际的浮点值。对于相关的调整阈值,使用{@code n - (n >>> 2)}等表达式更为简单。
* The actual floating point value isn't normally used -- it is
* simpler to use expressions such as {@code n - (n >>> 2)} for
* the associated resizing threshold.
*/
private static final float LOAD_FACTOR = 0.75f;
/**
* 使用tree而不是list的容器计数阈值。
* The bin count threshold for using a tree rather than list for a
* 当向至少有这么多节点的bin中添加元素时,bin将被转换为树。
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes.
* 该值必须大于2,并且应该至少为8,以便与tree移除时关于收缩后转换回普通bin的假设相吻合。
* The value must be greater
* than 2, and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 重新调整大小时,当元素个数小于这个阈值,将红黑树转成链表
* The bin count threshold for untreeifying a (split) bin during a
* 必须小于TREEIFY_THRESHOLD
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 链表转成红黑树时,table的最小size,否则只会对 table进行扩容
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* The value should be at least 4 * TREEIFY_THRESHOLD to avoid
* conflicts between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 每个转移步骤的最少rebinnings。范围被细分以允许多个调整大小的线程。
* Minimum number of rebinnings per transfer step. Ranges are
* subdivided to allow multiple resizer threads.
* 此值用作下限,以避免resizers遇到过多的内存争用。
* This value serves as a lower bound to avoid resizers encountering
* excessive memory contention. The value should be at least
* DEFAULT_CAPACITY.
*/
private static final int MIN_TRANSFER_STRIDE = 16;
/**
* 用于生成stamp的位数。
* The number of bits used for generation stamp in sizeCtl.
* Must be at least 6 for 32bit arrays.
*/
private static int RESIZE_STAMP_BITS = 16;
/**
* 可以帮助调整大小的最大线程数。
* The maximum number of threads that can help resize.
* Must fit in 32 - RESIZE_STAMP_BITS bits.
*/
// RESIZE_STAMP_BITS = 16 -> (1 << 16) - 1 = 65535
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
/**
* 用于在sizeCtl中记录大小戳的位移位。
* The bit shift for recording size stamp in sizeCtl.
*/
// RESIZE_STAMP_BITS = 16; RESIZE_STAMP_SHIFT = 32 - 16 = 16;
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
/*
* Encodings for Node hash fields. See above for explanation.
*/
static final int MOVED = -1; // hash for forwarding nodes
static final int TREEBIN = -2; // hash for roots of trees
// ReservationNode 使用的,computeIfAbsent()和compute()中占位使用的
static final int RESERVED = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
/** Number of CPUS, to place bounds on some sizings */
static final int NCPU = Runtime.getRuntime().availableProcessors();
/** For serialization compatibility. */
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("segments", Segment[].class),
new ObjectStreamField("segmentMask", Integer.TYPE),
new ObjectStreamField("segmentShift", Integer.TYPE)
};
/* ---------------- Nodes -------------- */
/**
* Key-value entry. This class is never exported out as a
* user-mutable Map.Entry (i.e., one supporting setValue; see
* MapEntry below), but can be used for read-only traversals used
* in bulk tasks. Subclasses of Node with a negative hash field
* are special, and contain null keys and values (but are never
* exported). Otherwise, keys and vals are never null.
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
// ForwardingNode 传入 (MOVED, null, null, null)
// TreeBin 传入 TREEBIN, null, null, null
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return val; }
public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
public final String toString(){ return key + "=" + val; }
// ConcurrentHashMap的更新操作需要获取锁,所以不支持直接修改值
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
public final boolean equals(Object o) {
Object k, v, u; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == (u = val) || v.equals(u)));
}
/**
* Virtualized support for map.get(); overridden in subclasses.
*/
Node<K,V> find(int h, Object k) {
Node<K,V> e = this;
if (k != null) {
do {
K ek;
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
} while ((e = e.next) != null);
}
return null;
}
}
/* ---------------- Static utilities -------------- */
/**
* 将(XORs)较高的散列位传播到较低的散列,并将最高位强制为0。
* Spreads (XORs) higher bits of hash to lower and also forces top
* 由于该表使用了power-of-two掩码,因此仅在当前掩码之上的位上变化的散列集总是会发生冲突。
* bit to 0. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* (已知的例子包括一组在小表中保存连续整数的浮点key。)
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* 因此,我们应用了一个转换,将更高位的影响向下传播。
* apply a transform that spreads the impact of higher bits
* 在速度、效用和位分布的质量之间存在权衡。
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading.
* 因为许多常见的散列集已经合理分布(所以不要受益于传播)
* Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading),
* 因为我们用树来处理箱子里的大量的碰撞,我们只是用最便宜的方式来XOR一些移位的位来减少系统的丢失,
* and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage,
* 以及合并最高位的影响,否则在索引计算中由于表的边界将永远不会使用
* as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int spread(int h) {
// (h ^ (h >>> 16)) 高16位不变,低16位取高16位与低16位 异或后的值
// HASH_BITS = 0x7fffffff. & HASH_BITS 的作用是,将最高位置为 0
return (h ^ (h >>> 16)) & HASH_BITS;
}
/**
* Returns a power of two table size for the given desired capacity.
* See Hackers Delight, sec 3.2
*/
// 返回大于等于c的最小的2的幂的数
private static final int tableSizeFor(int c) {
int n = c - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/**
* Returns x's Class if it is of the form "class C implements
* Comparable<C>", else null.
*/
// 判断x的类是否是 "class C implements Comparable<C>" 类型的
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
// c = x.getClass(), 并判断c是否是 String.class
if ((c = x.getClass()) == String.class) // bypass checks
// 如果是字符串,则通过检查
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
// p.getActualTypeArguments() 获取泛型类型
return c;
}
}
}
return null;
}
/**
* Returns k.compareTo(x) if x matches kc (k's screened comparable
* class), else 0.
*/
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
/* ---------------- Table element access -------------- */
/*
* Volatile access methods are used for table elements as well as
* elements of in-progress next table while resizing. All uses of
* the tab arguments must be null checked by callers. All callers
* also paranoically precheck that tab's length is not zero (or an
* equivalent check), thus ensuring that any index argument taking
* the form of a hash value anded with (length - 1) is a valid
* index. Note that, to be correct wrt arbitrary concurrency
* errors by users, these checks must operate on local variables,
* which accounts for some odd-looking inline assignments below.
* Note that calls to setTabAt always occur within locked regions,
* and so in principle require only release ordering, not
* full volatile semantics, but are currently coded as volatile
* writes to be conservative.
*/
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
// (long)i << ASHIFT) + ABASE -> 索引i 的地址偏移量
// 从给定的Java变量中获取一个具有volatile读取语义的引用值
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
// c -> expected
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
/* ---------------- Fields -------------- */
/**
* 在第一次插入时惰性初始化。
* The array of bins. Lazily initialized upon first insertion.
* 大小总是二的幂。由迭代器直接访问。
* Size is always a power of two. Accessed directly by iterators.
*/
// table 使用 volatile 修饰了
transient volatile Node<K,V>[] table;
/**
* 只有在扩容的时候是非空的
* The next table to use; non-null only while resizing.
*/
private transient volatile Node<K,V>[] nextTable;
/**
* 基本计数器值,主要在没有争用时使用,但也可作为表初始化竞争期间的回退。
* Base counter value, used mainly when there is no contention,
* but also as a fallback during table initialization
* races. Updated via CAS. 通过CAS更新
*/
private transient volatile long baseCount;
/**
* 表初始化和大小调整控件。当为负值时,表被初始化或调整大小:-1表示初始化,否则-(1 +活动调整大小的线程数)。
* Table initialization and resizing control. When negative, the
* table is being initialized or resized: -1 for initialization,
* else -(1 + the number of active resizing threads). Otherwise,
* 否则,当表为空时,保留创建时使用的初始表大小,默认为0。
* when table is null, holds the initial table size to use upon
* 初始化之后,保存下一个元素count值,根据该值调整表的大小。
* creation, or 0 for default. After initialization, holds the
* next element count value upon which to resize the table.
*/
private transient volatile int sizeCtl;
/**
* 调整大小时要分割的下一个表索引(加上一个)。
* The next table index (plus one) to split while resizing.
*/
private transient volatile int transferIndex;
/**
* 自旋锁(通过CAS来获取锁),CounterCells 创建、扩容的时候使用
* Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
*/
private transient volatile int cellsBusy;
/**
* 非空的时候大小为 2的幂
* Table of counter cells. When non-null, size is a power of 2.
*/
private transient volatile CounterCell[] counterCells;
// views
private transient KeySetView<K,V> keySet;
private transient ValuesView<K,V> values;
private transient EntrySetView<K,V> entrySet;
/* ---------------- Public operations -------------- */
/**
* Creates a new, empty map with the default initial table size (16).
*/
public ConcurrentHashMap() {
}
/**
* 创建一个新的空map,其初始表大小可容纳指定数量的元素,而不需要动态调整大小。
* Creates a new, empty map with an initial table size
* accommodating the specified number of elements without the need
* to dynamically resize.
*
* @param initialCapacity The implementation performs internal
* sizing to accommodate this many elements.
* @throws IllegalArgumentException if the initial capacity of
* elements is negative
*/
// initialCapacity 是 table 可容纳的元素个数,而不是 table 的 size
public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException();
// 若initialCapacity 大于等于MAXIMUM_CAPACITY的一半,直接设置为 MAXIMUM_CAPACITY,
// 否则设置为 tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1))
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
MAXIMUM_CAPACITY :
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
// 把 table的初始容量保存到 sizeCtl中
this.sizeCtl = cap;
}
/**
* Creates a new map with the same mappings as the given map.
*
* @param m the map
*/
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
// DEFAULT_CAPACITY = 16
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
}
/**
* Creates a new, empty map with an initial table size based on
* the given number of elements ({@code initialCapacity}) and
* initial table density ({@code loadFactor}).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements,
* given the specified load factor.
* @param loadFactor the load factor (table density) for
* establishing the initial table size
* @throws IllegalArgumentException if the initial capacity of
* elements is negative or the load factor is nonpositive
*
* @since 1.6
*/
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, 1);
}
/**
* Creates a new, empty map with an initial table size based on
* the given number of elements ({@code initialCapacity}), table
* density ({@code loadFactor}), and number of concurrently
* updating threads ({@code concurrencyLevel}).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements,
* given the specified load factor.
* @param loadFactor the load factor (table density) for
* establishing the initial table size
* @param concurrencyLevel the estimated number of concurrently
* updating threads. The implementation may use this value as
* a sizing hint.
* @throws IllegalArgumentException if the initial capacity is
* negative or the load factor or concurrencyLevel are
* nonpositive
*/
// initialCapacity 和 HashMap的 initialCapacity 不同。这里的initialCapacity表示能容纳的元素而不扩容
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
// 参数不能小于 0
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
// 计算table 的最小长度, +1 使table容纳 initialCapacity 个元素而不会扩容
// loadFactor 只会影响初始化时 table的初始容量
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
// 把size 转成小于MAXIMUM_CAPACITY的 2 的幂
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
// 把 table的长度保存到 sizeCtl中
this.sizeCtl = cap;
}
// Original (since JDK1.2) Map methods
/**
* {@inheritDoc}
*/
public int size() {
long n = sumCount();
// 若 size 大于 Integer.MAX_VALUE, 则返回 Integer.MAX_VALUE
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}
/**
* {@inheritDoc}
*/
// 判断集合是否有元素
public boolean isEmpty() {
// 插入一个元素后,还没有完成元素个数+1,然后瞬间就被另一个线程删除了,这种情况下就会
// 出现瞬间元素个数是负的
return sumCount() <= 0L; // ignore transient negative values 忽略瞬时负值
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key.equals(k)},
* then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* @throws NullPointerException if the specified key is null
*/
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
// 计算key的hash值,并将最高位置为0 (正数)
int h = spread(key.hashCode());
// 判断table 不为空,且 key对应的索引位置元素不为null
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
// 首先判断和第一个节点是否相等
if ((eh = e.hash) == h) {
// hash值相等,判断 key是否相等
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
// eh = e.hash, 小于0 说明该节点是TreeBin 或者ForwardingNode 节点,调用的相应子类的find()方法
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))))
// 找到,返回 key 映射的值
return e.val;
}
}
// 没找到返回null. ConcurrentHashMap 的 key 和 value 都不能为null, 所以返回null
// 说明key 不存在
return null;
}
/**
* 检查key是否存在
* Tests if the specified object is a key in this table.
*
* @param key possible key
* 当且仅当 key存在时返回true,由equals()方法确定, 否则返回false
* @return {@code true} if and only if the specified object
* is a key in this table, as determined by the
* {@code equals} method; {@code false} otherwise
* @throws NullPointerException if the specified key is null
*/
public boolean containsKey(Object key) {
// 调用get()方法,如果返回的值不为null,说明存在
// (因为key 和 value 都不允许为null。 HashMap调用的是getNode()方法)
return get(key) != null;
}
/**
* 如果有一个或者多个key 映射是指定的值,那么返回true。这个方法需要遍历整个
* map,并且比 containsKey() 方法慢得多
* Returns {@code true} if this map maps one or more keys to the
* specified value. Note: This method may require a full traversal
* of the map, and is much slower than method {@code containsKey}.
*
* 测试在这个map中存在的值
* @param value value whose presence in this map is to be tested
* @return {@code true} if this map maps one or more keys to the
* specified value
* @throws NullPointerException if the specified value is null
*/
public boolean containsValue(Object value) {
if (value == null)
throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
// 创建了一个 Traverser
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V v;
if ((v = p.val) == value || (v != null && value.equals(v)))
// 找到,返回true,不再继续遍历
return true;
}
}
// 没有找到,返回false
return false;
}
/**
* Maps the specified key to the specified value in this table.
* key 和 value 都不能为 null
* Neither the key nor the value can be null.
*
* value 可以用相同的key 通过 get()方法来获取
* <p>The value can be retrieved by calling the {@code get} method
* with a key that is equal to the original key.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* 返回key映射的上一个值,null表示key是第一次放入 table中
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* key / value 为 null 将抛出 NullPointerException
* @throws NullPointerException if the specified key or value is null
*/
public V put(K key, V value) {
return putVal(key, value, false);
}
// onlyIfAbsent -> 是否key 不存在才进行插入
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
// key 和 value 都不允许为 null
if (key == null || value == null) throw new NullPointerException();
// 分散 key 的哈希值, 并将最高位置为0 (保证 hash值都为正数)
int hash = spread(key.hashCode());
// binCount的计数个数不包含新插入的元素
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
// f -> first 的意思, key对应索引位置i上的第一个节点
// n -> table 的长度, i - > key 对应的索引位置 index, fh -> f节点的哈希值
Node<K,V> f; int n, i, fh;
// 若 table为null, 或者长度为0,则初始化 table
if (tab == null || (n = tab.length) == 0)
// 初始化 table
tab = initTable();
// (n - 1) & hash 计算 key 的索引位置
// 使用unsafe获取索引位置i的元素值(具有volatile读取语义)
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 使用CAS设置索引i位置的值 (CAS操作具有和 volatile相同读写内存语义)
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
// CAS设置成功,结束循环
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
// 使用锁而不能使用CAS的原因是: 1、比如该索引位置有:A -> B -> C 三个节点,
// 此时C.next = null,如果线程A要添加节点D,而线程B要删除节点C,如果线程B
// 在线程A之前把节点C删除了,而线程A又使用CAS把线程D添加到节点C的后面,那么
// 将导致节点D也被删除了;2、没办法控制插入和删除的并发问题
// 需要先拿到相应索引位置上第一个元素的锁
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)))) {
// key 已存在
oldVal = e.val;
if (!onlyIfAbsent)
// onlyIfAbsent = false 则使用新的值替换原来的值
e.val = value;
// binCount的元素计数个数不包含新插入的元素
break; // break 跳出循环,binCount不会再增加
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
// 因为进入这里需要先拿到第一个元素的锁,因此不需要使用CAS进行操作
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
// 添加到红黑树中
else if (f instanceof TreeBin) {
Node<K,V> p;
// binCount 设置为2,当存在竞争的时候可以进行扩容,当存在多线程竞争的时候 binCount <= 1,不会
// 进行扩容
binCount = 2;
// 如果 p != null,表示 key 映射的节点已经存在
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
// TREEIFY_THRESHOLD = 8。 binCount不包含新插入的元素,因此加上新插入的元素,slot中元素个数达到
// 9个才会转成红黑树,跟HashMap的 put()方法一样,也是9个元素才会转成红黑树
if (binCount >= TREEIFY_THRESHOLD)
// 把链表转成红黑树,注意:此时已经释放了锁
treeifyBin(tab, i);
if (oldVal != null)
// oldVal != null,说明只是使用了新的值替换原来的值,map中元素的个数不变,直接返回原来的值
return oldVal;
break;
}
}
}
// --------- for 循环结束 -------------
// binCount -> 同一个索引位置的元素个数,binCount的元素计数个数不包含新插入的元素
addCount(1L, binCount);
return null;
}
/**
* Copies all of the mappings from the specified map to this one.
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified map.
*
* @param m mappings to be stored in this map
*/
public void putAll(Map<? extends K, ? extends V> m) {
tryPresize(m.size());
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
putVal(e.getKey(), e.getValue(), false);
}
/**
* 从map中删除key(以及它映射的值)
* Removes the key (and its corresponding value) from this map.
* 如果key不存在map中,则这个方法不会做任何操作
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key is null
*/
public V remove(Object key) {
return replaceNode(key, null, null);
}
/**
* 实现4个公共删除/替换方法:用v替换节点值,条件是匹配cv(如果非null)。
* Implementation for the four public remove/replace methods:
* Replaces node value with v, conditional upon match of cv if
* 如果结果值为空,则删除。
* non-null. If resulting value is null, delete.
*/
// cv -> compareValue , cv != null时,只有key(若key存在)映射的值和cv相等
// 才会执行元素删除,或者替换元素的值。 删除、替换的判断依据是 value是否为null,
// value = null,删除元素,否则替换元素的值
// 返回替换、或者删除元素的值。如果没有替换/删除,那么就算key存在也是返回null
final V replaceNode(Object key, V value, Object cv) {
// 计算 key 的hash值
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
// n -> tab.length ; i -> key 对应的索引位置; fh -> f的hash值
Node<K,V> f; int n, i, fh;
// table为空 或者 对应的索引位置上没有元素
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
// 结束循环,返回null
break;
// 如果表正在扩容
else if ((fh = f.hash) == MOVED)
// 帮助转移元素
tab = helpTransfer(tab, f);
else {
V oldVal = null;
boolean validated = false;
// 获取索引位置第一个元素的锁
synchronized (f) {
// 获取到锁后需要判断该节点的第一个元素是否还是原来那个元素
if (tabAt(tab, i) == f) {
// fh >= 0 说明是该索引位置的节点链表结构
if (fh >= 0) {
validated = true;
// pred 表示遍历的上一个节点
for (Node<K,V> e = f, pred = null;;) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
// 找到key所在的节点
// 把元素的值赋值给 ev
V ev = e.val;
// cv -> compareValue , cv != null时,只有key(若key存在)映射的值和cv相等
// 才会执行元素删除,或者替换元素的值。 删除、替换的判断依据是 value是否为null,
// cv = null 或者 cv 和 ev相等 (如果cv != null,那么 cv 和 ev相等才会删除元素
// 或者替换元素的值)
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
// 把ev 赋值给 oldValue, 如果 cv != null,且 cv和cv不相等,
// 那么就算key 存在也是返回null
oldVal = ev;
if (value != null)
// 如果 value != null,则元素的值替换为 value
e.val = value;
// 注意:删除节点时不能修改删除节点的信息,因为有可能其他线程正在遍历该节点
else if (pred != null) {
// value = null, pred != null,则pred的下一个元素指向
// e的下一个元素,即把 e 删除掉
pred.next = e.next;
}
else
// value = null 且 pred = null,说明删除的节点是第一个节点,把该索引位置
// 的第一个元素设置为e.next,即把 e 删除掉 (e.next可能为null)
setTabAt(tab, i, e.next);
}
// 结束内循环,此时 validated = true,因此外循环也会结束
break;
}
// 节点e不是key所在的节点, pred = e
pred = e;
// 该索引位置上没有下一个元素了,结束循环,返回null
if ((e = e.next) == null)
// 结束内循环,此时 validated = true,因此外循环也会结束
break;
}
// ----- 内层 for 循环结束
}
// 前面已经拿到了第一个元素的锁 (不论是链表还是树结构,只要是更新操作都需要获取到第一个元素的锁)
else if (f instanceof TreeBin) {
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
// r = t.root 获取根节点
if ((r = t.root) != null &&
// 从红黑中查找,如果存在返回相应的节点,否则返回null
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
// cv = null 或者 cv 和 ev相等 (如果cv != null,那么 cv 和 ev相等才会删除元素
// 或者替换元素的值)
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
// 把ev 赋值给 oldValue, 如果 cv != null,且 cv和cv不相等,
// 那么就算key 存在也是返回null
oldVal = pv;
if (value != null)
// value != null,替换元素的值
p.val = value;
// 删除p 节点,返回true表示树结构太小,需要转成链表
else if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
// validated = false的情况:获取到锁后第一个元素不是原来那个元素了,或者第一个节点的hash值小于0且不是 TreeBin节点
// validated = false 说明需要继续循环, validated = true,则判断元素个数个数应该 -1,然后
// 返回原来的值,返回null (key不存在返回 null)
if (validated) {
// key 存在,且 cv = null 或者 cv 和 key 映射的值相等时 oldVal才会不为 null
if (oldVal != null) {
if (value == null)
// oldVal != null, value = null,说明 key所在的节点已经被删除,
// 元素个数减1, check传入 -1,表示不用进行是否扩容的判断
addCount(-1L, -1);
// oldVal != null,则返回 oldVal
return oldVal;
}
// oldVal = null,则结束循环,返回 null
break;
}
}
}
return null;
}
/**
* Removes all of the mappings from this map.
*/
public void clear() {
// 删除为负值
long delta = 0L; // negative number of deletions
int i = 0;
Node<K,V>[] tab = table;
while (tab != null && i < tab.length) {
int fh;
Node<K,V> f = tabAt(tab, i);
if (f == null)
// 该索引位置上没有元素,遍历下一个元素
++i;
// 索引i前面的元素都已经删除掉了,索引i后面的元素正常情况下都已经搬移都新的table了,因为搬移
// 是从后往前搬移的,但是多线程同时执行helpTransfer()时可能还有个别索引位置的元素还没有完成搬移
else if ((fh = f.hash) == MOVED) {
// 当前正在进行扩容,帮忙转移元素, helpTransfer()会返回新的table
tab = helpTransfer(tab, f);
i = 0; // restart
}
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
// 获取该索引位置的第一个元素
Node<K,V> p = (fh >= 0 ? f :
(f instanceof TreeBin) ?
((TreeBin<K,V>)f).first : null);
while (p != null) {
// 只要计算该索引位置上有几个元素就可以了,把该索引位置的元素设置为null
// 进行一次性删除
--delta;
p = p.next;
}
// 设置该索引位置上的元素为null,然后 i++
setTabAt(tab, i++, null);
}
}
}
}
// 更新元素个数
if (delta != 0L)
addCount(delta, -1);
}
/**
* 返回这个map中包含的keys的一个set集合
* Returns a {@link Set} view of the keys contained in this map.
* 集合由map支持,因此对map的更改将反映在集合中,反之亦然。
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* 这个set集合支持元素移除,即从这个map中移除对应的映射,
* removal, which removes the corresponding mapping from this map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* 它不支持add或addAll操作。
* operations. It does not support the {@code add} or
* {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
*
* @return the set view
*/
// 注意: 返回的Set不支持add或addAll操作。
public KeySetView<K,V> keySet() {
KeySetView<K,V> ks;
// value 传入null,因此不支持增加元素
return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
}
/**
* 返回这个map中的values的一个集合视图。
* Returns a {@link Collection} view of the values contained in this map.
* 这个集合由这个map支持,因此对这个map的修改会反映到这个集合中,反之亦然。
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. The collection
* 这个集合支持元素移除,即从map中移除相应的映射。
* supports element removal, which removes the corresponding
* mapping from this map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll}, and {@code clear} operations. It does not
* 它不支持add或addAll操作。
* support the {@code add} or {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
* and {@link Spliterator#NONNULL}.
*
* @return the collection view
*/
public Collection<V> values() {
ValuesView<K,V> vs;
// 创建ValuesView
return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
*
* @return the set view
*/
public Set<Map.Entry<K,V>> entrySet() {
EntrySetView<K,V> es;
return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
}
/**
* Returns the hash code value for this {@link Map}, i.e.,
* the sum of, for each key-value pair in the map,
* {@code key.hashCode() ^ value.hashCode()}.
*
* @return the hash code value for this map
*/
public int hashCode() {
int h = 0;
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; )
h += p.key.hashCode() ^ p.val.hashCode();
}
return h;
}
/**
* Returns a string representation of this map. The string
* representation consists of a list of key-value mappings (in no
* particular order) enclosed in braces ("{@code {}}"). Adjacent
* mappings are separated by the characters {@code ", "} (comma
* and space). Each key-value mapping is rendered as the key
* followed by an equals sign ("{@code =}") followed by the
* associated value.
*
* @return a string representation of this map
*/
public String toString() {
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
StringBuilder sb = new StringBuilder();
sb.append('{');
Node<K,V> p;
if ((p = it.advance()) != null) {
for (;;) {
K k = p.key;
V v = p.val;
sb.append(k == this ? "(this Map)" : k);
sb.append('=');
sb.append(v == this ? "(this Map)" : v);
if ((p = it.advance()) == null)
break;
sb.append(',').append(' ');
}
}
return sb.append('}').toString();
}
/**
* Compares the specified object with this map for equality.
* Returns {@code true} if the given object is a map with the same
* mappings as this map. This operation may return misleading
* results if either map is concurrently modified during execution
* of this method.
*
* @param o object to be compared for equality with this map
* @return {@code true} if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o != this) {
if (!(o instanceof Map))
return false;
Map<?,?> m = (Map<?,?>) o;
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V val = p.val;
Object v = m.get(p.key);
if (v == null || (v != val && !v.equals(val)))
return false;
}
for (Map.Entry<?,?> e : m.entrySet()) {
Object mk, mv, v;
if ((mk = e.getKey()) == null ||
(mv = e.getValue()) == null ||
(v = get(mk)) == null ||
(mv != v && !mv.equals(v)))
return false;
}
}
return true;
}
/**
* Stripped-down version of helper class used in previous version,
* declared for the sake of serialization compatibility
*/
static class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
final float loadFactor;
Segment(float lf) { this.loadFactor = lf; }
}
/**
* Saves the state of the {@code ConcurrentHashMap} instance to a
* stream (i.e., serializes it).
* @param s the stream
* @throws java.io.IOException if an I/O error occurs
* @serialData
* the key (Object) and value (Object)
* for each key-value mapping, followed by a null pair.
* The key-value mappings are emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// For serialization compatibility
// Emulate segment calculation from previous version of this class
int sshift = 0;
int ssize = 1;
while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
++sshift;
ssize <<= 1;
}
int segmentShift = 32 - sshift;
int segmentMask = ssize - 1;
@SuppressWarnings("unchecked")
Segment<K,V>[] segments = (Segment<K,V>[])
new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
for (int i = 0; i < segments.length; ++i)
segments[i] = new Segment<K,V>(LOAD_FACTOR);
s.putFields().put("segments", segments);
s.putFields().put("segmentShift", segmentShift);
s.putFields().put("segmentMask", segmentMask);
s.writeFields();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
s.writeObject(p.key);
s.writeObject(p.val);
}
}
s.writeObject(null);
s.writeObject(null);
segments = null; // throw away
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
* @param s the stream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
/*
* To improve performance in typical cases, we create nodes
* while reading, then place in table once size is known.
* However, we must also validate uniqueness and deal with
* overpopulated bins while doing so, which requires
* specialized versions of putVal mechanics.
*/
sizeCtl = -1; // force exclusion for table construction
s.defaultReadObject();
long size = 0L;
Node<K,V> p = null;
for (;;) {
@SuppressWarnings("unchecked")
K k = (K) s.readObject();
@SuppressWarnings("unchecked")
V v = (V) s.readObject();
if (k != null && v != null) {
p = new Node<K,V>(spread(k.hashCode()), k, v, p);
++size;
}
else
break;
}
if (size == 0L)
sizeCtl = 0;
else {
int n;
if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
n = MAXIMUM_CAPACITY;
else {
int sz = (int)size;
n = tableSizeFor(sz + (sz >>> 1) + 1);
}
@SuppressWarnings("unchecked")
Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
int mask = n - 1;
long added = 0L;
while (p != null) {
boolean insertAtFront;
Node<K,V> next = p.next, first;
int h = p.hash, j = h & mask;
if ((first = tabAt(tab, j)) == null)
insertAtFront = true;
else {
K k = p.key;
if (first.hash < 0) {
TreeBin<K,V> t = (TreeBin<K,V>)first;
if (t.putTreeVal(h, k, p.val) == null)
++added;
insertAtFront = false;
}
else {
int binCount = 0;
insertAtFront = true;
Node<K,V> q; K qk;
for (q = first; q != null; q = q.next) {
if (q.hash == h &&
((qk = q.key) == k ||
(qk != null && k.equals(qk)))) {
insertAtFront = false;
break;
}
++binCount;
}
if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
insertAtFront = false;
++added;
p.next = first;
TreeNode<K,V> hd = null, tl = null;
for (q = p; q != null; q = q.next) {
TreeNode<K,V> t = new TreeNode<K,V>
(q.hash, q.key, q.val, null, null);
if ((t.prev = tl) == null)
hd = t;
else
tl.next = t;
tl = t;
}
setTabAt(tab, j, new TreeBin<K,V>(hd));
}
}
}
if (insertAtFront) {
++added;
p.next = first;
setTabAt(tab, j, p);
}
p = next;
}
table = tab;
sizeCtl = n - (n >>> 2);
baseCount = added;
}
}
// ConcurrentMap methods
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V putIfAbsent(K key, V value) {
return putVal(key, value, true);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the specified key is null
*/
public boolean remove(Object key, Object value) {
if (key == null)
throw new NullPointerException();
return value != null && replaceNode(key, null, value) != null;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if any of the arguments are null
*/
public boolean replace(K key, V oldValue, V newValue) {
if (key == null || oldValue == null || newValue == null)
throw new NullPointerException();
return replaceNode(key, newValue, oldValue) != null;
}
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V replace(K key, V value) {
if (key == null || value == null)
throw new NullPointerException();
return replaceNode(key, value, null);
}
// Overrides of JDK8+ Map extension method defaults
/**
* Returns the value to which the specified key is mapped, or the
* given default value if this map contains no mapping for the
* key.
*
* @param key the key whose associated value is to be returned
* @param defaultValue the value to return if this map contains
* no mapping for the given key
* @return the mapping for the key, if present; else the default value
* @throws NullPointerException if the specified key is null
*/
public V getOrDefault(Object key, V defaultValue) {
V v;
return (v = get(key)) == null ? defaultValue : v;
}
public void forEach(BiConsumer<? super K, ? super V> action) {
if (action == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
action.accept(p.key, p.val);
}
}
}
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
if (function == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V oldValue = p.val;
for (K key = p.key;;) {
V newValue = function.apply(key, oldValue);
if (newValue == null)
throw new NullPointerException();
if (replaceNode(key, newValue, oldValue) != null ||
(oldValue = get(key)) == null)
break;
}
}
}
}