Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
性能不佳的原因可能是什么?
最佳答案
在内部,java.util.Random 保留一个带有当前种子的 AtomicLong,每当请求一个新的随机数时,就会争用更新种子。
来自 java.util.Random 的实现:
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
另一方面,ThreadLocalRandom 通过每个线程有一个种子来确保更新种子而不会面临任何争用。
关于java - 并发使用 java.util.Random 的争用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313552/