Java并发编程

Java并发编程 - ThreadLocalRandom

2019-05-22  本文已影响2人  HRocky

Random类的API文档描述中有这样的一句话:

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类的实例是线程安全的。然而,跨线程并发的情况下使用java.util.Random实例会产生竞争,从而导致性能不佳。在多线程设计中考虑使用ThreadLocalRandom。

我们知道,Random类使用线性同余的方式来生成伪随机数。在创建Random类的实例时会确定用于生成随机数的称为"种子"的数,这个"种子"在调用随机数生成方法后会重新被计算并且进行重设,内部代码使用的CAS操作来保证并发过程中的原子性,如下:

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));
}

上面说得多线程并发的情况出现争用,说得就是对这个"种子"的重设操作。使用无锁的CAS算法保证了Random是线程安全的,但是由于还是要处理争用,所以还是会影响性能。

ThreadLocalRandom就是用来解决多线程并发的情况下生成随机数的性能问题。"ThreadLocal"这个词应该很熟悉了吧,从这个类的取名也就看出,它的实例是线程隔离的。

这个类的用法通常应该是这样的形式: ThreadLocalRandom.current().nextX(...) (其中X是Int , Long ,等)。 当所有用法都是这种形式时,绝对不可能跨多个线程共享一个ThreadLocalRandom 。

current()

current()方法代码如下:

/**
 * Returns the current thread's {@code ThreadLocalRandom}.
 *
 * @return the current thread's {@code ThreadLocalRandom}
 */
public static ThreadLocalRandom current() {
    if (UNSAFE.getInt(Thread.currentThread(), PROBE) == 0)
        localInit();
    return instance;
}

这个方法的作用如其注释所示:返回当前线程的ThreadLocalRandom。

UNSAFE.getInt(Thread.currentThread(), PROBE) == 0

这段代码的作用是判断当前线程的threadLocalRandomProbe属性是否为0。

PROBE定义如下:

Class<?> tk = Thread.class;
PROBE = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("threadLocalRandomProbe"));

Thread类定义了一个名为threadLocalRandomProbe的属性:

/** Probe hash value; nonzero if threadLocalRandomSeed initialized */
@sun.misc.Contended("tlr")
int threadLocalRandomProbe;

若当前线程的threadLocalRandomProbe这个探针属性还为设置,则执行localInit()方法。

这里要注意,执行完localInit方法后会返回ThreadLocalRandom实例,也就是方法中看到的instance的,instance的定义如下:

/** The common ThreadLocalRandom */
static final ThreadLocalRandom instance = new ThreadLocalRandom();

可以看到这个相当于一个单例。也就是说多线程的情况下都统一调用current()方法,那么返回的就是同一个ThreadLocalRandom实例。

localInit()

localInit()方法源码如下:

/**
 * Initialize Thread fields for the current thread.  Called only
 * when Thread.threadLocalRandomProbe is zero, indicating that a
 * thread local seed value needs to be generated. Note that even
 * though the initialization is purely thread-local, we need to
 * rely on (static) atomic generators to initialize the values.
 */
static final void localInit() {
    int p = probeGenerator.addAndGet(PROBE_INCREMENT);
    int probe = (p == 0) ? 1 : p; // skip 0
    long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
    Thread t = Thread.currentThread();
    UNSAFE.putLong(t, SEED, seed);
    UNSAFE.putInt(t, PROBE, probe);
}

上面的方法会生成"种子"和"探针"值,然后设置到当前线程中。Thread类中有存储"种子"的属性,如下:

java.lang.Thread

/** The current seed for a ThreadLocalRandom */
@sun.misc.Contended("tlr")
long threadLocalRandomSeed;

nextInt()

nextInt()源代码如下:

/**
 * Returns a pseudorandom {@code int} value.
 *
 * @return a pseudorandom {@code int} value
 */
public int nextInt() {
    return mix32(nextSeed());
}

final long nextSeed() {
    Thread t; long r; // read and update per-thread seed
    UNSAFE.putLong(t = Thread.currentThread(), SEED,
                   r = UNSAFE.getLong(t, SEED) + GAMMA);
    return r;
}

可以看到操作是线程独立的,当在多线程的环境下调用nextInt()方法时,每次都是通过当前线程内部的"种子"来生成随机数,线程与线程之间是没有干扰的。

总结

ThreadLocalRandom适用于多线程,是因为"种子"不再像Random类那样多线程共享,而是每个线程内部都保留着一个属于自己的"种子",线程操作的是这个线程局部的"种子",避免了生成随机数时"种子"的争抢,从而提升性能。

上一篇 下一篇

猜你喜欢

热点阅读