关于 ConcurrentHashMap 1.8 中的线程探针哈希
ConcurrentHashMap 在累加鍵值對個數的 addCount 函數中,使用 ThreadLocalRandom.getProbe() 得到線程的探針哈希值。
在這里,這個探針哈希值的作用是哈希線程,盡量避免線程爭用同一數組元素。探針哈希值和 map 里使用的哈希值的區別是,當線程發生數組元素爭用后,可以改變線程的探針哈希值,讓線程去使用另一個數組元素,而 map 中 key 對象的哈希值,由于有定位 value 的需求,所以它是一定不能變的。
那么這個探針哈希值是在哪計算的呢?帶著這個問題我們繼續往下看。
ThreadLocalRandom.getProbe() 方法如下:
PROBE 是什么?
// Unsafe mechanicsprivate static final sun.misc.Unsafe UNSAFE;...private static final long PROBE;...static {try {UNSAFE = sun.misc.Unsafe.getUnsafe();Class<?> tk = Thread.class;...PROBE = UNSAFE.objectFieldOffset(tk.getDeclaredField("threadLocalRandomProbe"));...} catch (Exception e) {throw new Error(e);}}可以看到 PROBE 表示的是 Thread 類 threadLocalRandomProbe 字段的偏移量。
所以 getProbe 方法的功能就是簡單的返回當前線程 threadLocalRandomProbe 字段的值。
接著去 Thread 類看看這個 threadLocalRandomProbe 字段,
/** Probe hash value; nonzero if threadLocalRandomSeed initialized */@sun.misc.Contended("tlr")int threadLocalRandomProbe;Thread 類僅僅是定義了這個字段,并沒有將其初始化,其初始化工作由 ThreadLocalRandom 類來做。
ThreadLocalRandom 類的 localInit 方法完成初始化工作,
SEED 和 PROBE 類似,它表示的是 Thread 類 threadLocalRandomSeed 字段的偏移量。
在 ThreadLocalRandom 類的這個 localInit 方法里,同時初始化了當前線程的 threadLocalRandomSeed 字段和 threadLocalRandomProbe 字段。
所以在 Thread 類 threadLocalRandomProbe 字段上的注釋中說:nonzero if threadLocalRandomSeed initialized。就是說如果 threadLocalRandomSeed 字段被初始化了,threadLocalRandomProbe 字段就非零。因為它倆是同時被初始化的。
除此之外,也可以通過 ThreadLocalRandom 類的 advanceProbe 方法更改當前線程 threadLocalRandomProbe 的值。
/*** Pseudo-randomly advances and records the given probe value for the* given thread.*/static final int advanceProbe(int probe) {probe ^= probe << 13; // xorshiftprobe ^= probe >>> 17;probe ^= probe << 5;UNSAFE.putInt(Thread.currentThread(), PROBE, probe);return probe;}ConcurrentHashMap 里的 fullAddCount 方法會調用 ThreadLocalRandom.localInit() 初始化當前線程的探針哈希值;當發生線程爭用后,也會調用 ThreadLocalRandom.advanceProbe(h) 更改當前線程的探針哈希值,
private final void fullAddCount(long x, boolean wasUncontended) {int h;if ((h = ThreadLocalRandom.getProbe()) == 0) {ThreadLocalRandom.localInit(); // force initializationh = ThreadLocalRandom.getProbe();wasUncontended = true;}...h = ThreadLocalRandom.advanceProbe(h);...}總結
以上是生活随笔為你收集整理的关于 ConcurrentHashMap 1.8 中的线程探针哈希的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你媳妇胖么?嘿嘿~
- 下一篇: 视频压缩技术及安卓中用法