java中ThreadLocalRandom的使用

在java中我們通常會需要使用到java.util.Random來便利的生產隨機數。但是Random是線程安全的,如果要在線程環境中的話就有可能產生性能瓶頸。

我們以Random中常用的nextInt方法為例來具體看一下:

<code>    public int nextInt() {
return next(32);
}
/<code>

Java

nextInt方法實際上調用了下面的方法:

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

Java

從代碼中我們可以看到,方法內部使用了AtomicLong,並調用了它的compareAndSet方法來保證線程安全性。所以這個是一個線程安全的方法。

其實在多個線程環境中,Random根本就需要共享實例,那麼該怎麼處理呢?

在JDK 7 中引入了一個ThreadLocalRandom的類。ThreadLocal大家都知道就是線程的本地變量,而ThreadLocalRandom就是線程本地的Random。

我們看下怎麼調用:

<code>ThreadLocalRandom.current().nextInt();
/<code>

Java

我們來為這兩個類分別寫一個benchMark測試:

<code>public class RandomUsage {

public void testRandom() throws InterruptedException {
ExecutorService executorService=Executors.newFixedThreadPool(2);
Random random = new Random();
List<callable>> callables = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
callables.add(() -> {
return random.nextInt();
});
}
executorService.invokeAll(callables);
}

public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(RandomUsage.class.getSimpleName())
// 預熱5輪
.warmupIterations(5)
// 度量10輪
.measurementIterations(10)
.forks(1)
.build();

new Runner(opt).run();
}
}
/<callable>/<code>

Java

<code>public class ThreadLocalRandomUsage {

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void testThreadLocalRandom() throws InterruptedException {
ExecutorService executorService=Executors.newFixedThreadPool(2);
List<callable>> callables = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
callables.add(() -> {
return ThreadLocalRandom.current().nextInt();
});

}
executorService.invokeAll(callables);
}

public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(ThreadLocalRandomUsage.class.getSimpleName())
// 預熱5輪
.warmupIterations(5)
// 度量10輪
.measurementIterations(10)
.forks(1)
.build();

new Runner(opt).run();
}
}
/<callable>/<code>

Java

分析運行結果,我們可以看出ThreadLocalRandom在多線程環境中會比Random要快。

更多內容請訪問:flydean的博客


分享到:


相關文章: