ThreadLocalRandom in JDK 17 and above (up to JDK 21):
@Override
public int nextInt(int bound) {
return super.nextInt(bound);
}
@Override
public int nextInt(int origin, int bound) {
return super.nextInt(origin, bound);
}
The methods nextXXX in ThreadLocalRandom implement directly with the super's (Random's) methods. In this way, I guess the ThreadLocalRandom is not "ThreadLocal"ed any more with respect to these methods.
I also check the same methods of ThreadLocalRandom in JDK8 like:
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);
int r = mix32(nextSeed());
int m = bound - 1;
if ((bound & m) == 0) // power of two
r &= m;
else { // reject over-represented candidates
for (int u = r >>> 1;
u + m - (r = u % bound) < 0;
u = mix32(nextSeed()) >>> 1)
;
}
return r;
}
My question is, what's the point that thosenextXXX implement with super.nextXXX() directly in JDK17 (even the first revision comes from older JDK version, which I did not justify) and above, which makes ThreadLocalRandom just a pure Random.
JEP 356 proposes to unify the various random number generators. It notes that the algorithm in
RandomandThreadLocalRandomare similar enough to unify them.That the methods
ThreadLocalRandom.nextInt(bound)andThreadLocalRandom.nextInt(origin, bound)are still there is because the JavaDoc for these methods is different from the JavaDoc forRandom.nextInt(bound)andRandom.nextInt(origin, bound).Internally, the methods in
Randomusenext(int)and / ornextInt(), both of which are overriden byThreadLocalRandom. That means even though the apparent implementation inThreadLocalRandomdisappeared aThreadLocalRandomis still a trueThreadLocalRandom.