spread方法是ConcurrentHashMap中的一个辅助方法,它用于在哈希表扩容时分散元素。在Java中,ConcurrentHashMap使用了一种名为“扩容重分配”(resizing/rehashing)的机制来处理动态大小调整的需求。spread方法就是用来在这个过程中计算新的哈希表索引位置的。
这个方法接收一个整数hash作为输入,并返回一个新的哈希值。它通过按位异或(^)和无符号右移(>>>)操作来混淆原始哈希值的高低位,进一步分散哈希值的分布。
这个方法不是公开API的一部分,因此不推荐在应用程序代码中直接使用。如果你需要一个类似的哈希分散功能,你应该考虑自行实现或者使用其他的哈希分散函数。
/**
* 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. 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), 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) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
Spreads (XORs) higher bits of hash to lower and also forces top bit to 0.
将哈希值的高位扩展(异或)到低位,并强制将高位 置为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.
所以我们应用一个转换,用于把高位的影响扩张到低位
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), and because we use trees to handle large sets of collisions in bins,
因为许多普通hash集合已经合理的分布(所以未从扩张中获益),而且我们使用 红黑树 去处理位于同一个桶中的hash
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.
以及合并高位的影响,否则可能会出现因为表边界导致计算出来的下标永远不会用到。
copy by https://www.cnblogs.com/brave-rocker/p/13338062.html