'Why do I always get the same result when using a ThreadLocalRandom class member?

In my Spring app, if I have a ThreadLocalRandom class member that is set during construction:

public class RNG {
  private ThreadLocalRandom rng;
  
  public RNG() {
    rng = ThreadLocalRandom.current();
  }
  
  public int getInt() {
    return rng.nextInt(1000, 10000);
  }
}

// some other class
RNG a = new RNG();
a.getInt();

The first int that's returned is always the same, even across restarts of the app. If I instead modify the getInt() method:

public int getInt() {
  return ThreadLocalRandom.current().nextInt(1000, 10000);
}

I'll get psuedo-random values every time, even across restarts of the app (which is what I expect). This seems to only happen in Spring; I've tried the same in jshell and Replit and don't see this behavior. For context, the Spring bean that generates the random number is autowired.

To be completely honest, I've removed random number generation from that part of the code altogether, and use an injected dependency instead, so I can unit test it.

This question is for me to get a better understanding of what is happening. As far as I'm aware, setting the class member during construction should provide a different value across restarts of the app.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source