Java 8:
现在,根本不使用固定的锁条带化方案,而是使用内部同步将每个存储桶用作“条带”。ConcurrentHashMap
来自源代码的代码:
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
...
Node<K,V> f; int n, i, fh;
...
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
...
synchronized (f) {
...
}
}
并且构造函数的参数只是像文档所说的那样将其用作大小提示。
并发级别 - 估计的并发更新线程数。实现可以将此值用作大小调整提示。
来源:
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
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
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
所以你不需要自己考虑,会为你处理。ConcurrentHashMap