Last active
October 1, 2021 15:41
-
-
Save YazidLee/81c247c9e73cbec6b42748fac5798d17 to your computer and use it in GitHub Desktop.
[ThreadLocal Hash] ThreadLocalMap中Entry的hashcode生成方式 #Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ThreadLocals rely on per-thread linear-probe hash maps attached | |
* to each thread (Thread.threadLocals and | |
* inheritableThreadLocals). The ThreadLocal objects act as keys, | |
* searched via threadLocalHashCode. This is a custom hash code | |
* (useful only within ThreadLocalMaps) that eliminates collisions | |
* in the common case where consecutively constructed ThreadLocals | |
* are used by the same threads, while remaining well-behaved in | |
* less common cases. | |
*/ | |
private final int threadLocalHashCode = nextHashCode(); | |
/** | |
* The next hash code to be given out. Updated atomically. Starts at | |
* zero. | |
*/ | |
private static AtomicInteger nextHashCode = | |
new AtomicInteger(); | |
/** | |
* The difference between successively generated hash codes - turns | |
* implicit sequential thread-local IDs into near-optimally spread | |
* multiplicative hash values for power-of-two-sized tables. | |
* 使用0x61c88647为递增间隔,能使Entry在长度为2的n次方的长度上分布均匀 | |
*/ | |
private static final int HASH_INCREMENT = 0x61c88647; | |
/** | |
* Returns the next hash code. | |
*/ | |
private static int nextHashCode() { | |
return nextHashCode.getAndAdd(HASH_INCREMENT); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment