并发使用java.util.Random的争用

Oracle Java documentation说:

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通过每个线程有一个种子来确保种子更新而不面对任何争用.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...