package leetcode0606.JUC.ConcurrentHashMap;
import java.util.HashMap;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
public class BasicMethod {
// 扰动哈希函数
// & HASH_BITS 是为了保证哈希值为正数
// h ^ (h >>> 16) 此算法与hashmap相同
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
// 利用访问内存的方式 拿到数据,底层用C++实现,直接访问内存
// 获取数组指定下标的元素 下标的内存地址:(long)i << ASHIFT) + ABASE
@SuppressWarnings("unchecked")
static final <K,V> ConcurrentHashMap.Node<K,V> tabAt(ConcurrentHashMap.Node<K,V>[] tab, int i) {
return (ConcurrentHashMap.Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
// 利用CAS机制去设定value
static final <K,V> boolean casTabAt(ConcurrentHashMap.Node<K,V>[] tab, int i,
ConcurrentHashMap.Node<K,V> c, ConcurrentHashMap.Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
// 直接set value
static final <K,V> void setTabAt(ConcurrentHashMap.Node<K,V>[] tab, int i, ConcurrentHashMap.Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
// 扩容时创建一个 唯一标识戳
// 假如从16--->32.
// Integer.numberOfLeadingZeros(16) = 32 - 5 = 27
// (1 << (RESIZE_STAMP_BITS - 1)) = 1 << (16-1) = 15 = 1000 0000 0000 0000 = 32768
// 27 --- 0000 0000 0001 1011
// 32678-- 1000 0000 0000 0000
// | -- 1000 0000 0001 1011
static final int resizeStamp(int n) {
return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
// 返回>=c 的最小的 2的次方数
// tableSizeFor(28) = 32;
// tableSizeFor(16) = 16;
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;
}
// 懒加载的,put操作时才会真正创建table
// Creates a new, empty map with the default initial table size (16).
public ConcurrentHashMap() {
}
// 有参构造
// 传入25--->创建32大小的数组
public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException();
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
MAXIMUM_CAPACITY :
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
// sizeCtl >0 时候
// 当目前的table未初始化时,sizeCtl表示初始化容量
this.sizeCtl = cap;
}
}
ConcurrentHashMap 基本方法解读
于 2022-08-29 18:43:50 首次发布