HashMap和ConcurrentHashMap中的hash函数     所属分类 java 浏览量 393
```hashmap中的hash函数

java7

final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}

h ^= k.hashCode();

// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

java8
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

ConcurrentHashMap 中的hash函数

Java7

private int hash(Object k) {
int h = hashSeed;

if ((0 != h) && (k instanceof String)) {
return sun.misc.Hashing.stringHash32((String) k);
}

h ^= k.hashCode();

// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h <<  15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h <<   3);
h ^= (h >>>  6);
h += (h <<   2) + (h << 14);
return h ^ (h >>> 16);
}

java8

static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}

Spreads (XORs) higher bits of hash to lower and also forces top bit to 0.
Because the table uses power-of-two masking, sets of hashes that vary only in bits above the current mask will 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.
Because many common sets of hashes are already reasonably distributed
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.

(已知的例子包括在小表中保存连续整数的浮点键集。)

```

java8 hashmap 要点

hashmap在java7和8中的区别

java位运算

ConcurrentHashMap读不需要加锁的秘密

ConcurrentHashMap size 实现要点

37种融资模式