加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:16:48 所属栏目:Java 来源:网络整理
导读: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 Th
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通过每个线程有一个种子来确保种子更新而不面对任何争用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读