Search code examples
javarandomthread-local

JDK 21 - Why ThreadLocalRandom's nextInt implement with super.nextInt directly?


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.


Solution

  • JEP 356 proposes to unify the various random number generators. It notes that the algorithm in Random and ThreadLocalRandom are similar enough to unify them.

    That the methods ThreadLocalRandom.nextInt(bound) and ThreadLocalRandom.nextInt(origin, bound) are still there is because the JavaDoc for these methods is different from the JavaDoc for Random.nextInt(bound) and Random.nextInt(origin, bound).

    Internally, the methods in Random use next(int) and / or nextInt(), both of which are overriden by ThreadLocalRandom. That means even though the apparent implementation in ThreadLocalRandom disappeared a ThreadLocalRandom is still a true ThreadLocalRandom.