java中ThreadLocalRandom的使用

在java中我们通常会需要使用到java.util.Random来便利的生产随机数。但是Random是线程安全的,如果要在线程环境中的话就有可能产生性能瓶颈。

我们以Random中常用的nextInt方法为例来具体看一下:

    public int nextInt() {
return next(32);
}

nextInt方法实际上调用了下面的方法:

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

从代码中我们可以看到,方法内部使用了AtomicLong,并调用了它的compareAndSet方法来保证线程安全性。所以这个是一个线程安全的方法。

其实在多个线程环境中,Random根本就需要共享实例,那么该怎么处理呢?

在JDK 7 中引入了一个ThreadLocalRandom的类。ThreadLocal大家都知道就是线程的本地变量,而ThreadLocalRandom就是线程本地的Random。

我们看下怎么调用:

ThreadLocalRandom.current().nextInt();

我们来为这两个类分别写一个benchMark测试:

public class RandomUsage {

    public void testRandom() throws InterruptedException {
ExecutorService executorService=Executors.newFixedThreadPool(2);
Random random = new Random();
List<Callable<Integer>> 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();
}
}
public class ThreadLocalRandomUsage {

    @Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void testThreadLocalRandom() throws InterruptedException {
ExecutorService executorService=Executors.newFixedThreadPool(2);
List<Callable<Integer>> 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();
}
}

分析运行结果,我们可以看出ThreadLocalRandom在多线程环境中会比Random要快。

本文的例子可以参考https://github.com/ddean2009/learn-java-concurrency/tree/master/ThreadLocalRandom

更新文章请参考flydean的博客

java中ThreadLocalRandom的使用的更多相关文章

  1. java中ThreadLocalRandom类和Random类的使用

    package frank; import java.lang.*; import java.util.*;//工具类一般都在util里面 import java.util.concurrent.Th ...

  2. Java中的随机数生成器:Random,ThreadLocalRandom,SecureRandom

    Java中的随机数生成器:Random,ThreadLocalRandom,SecureRandom 文中的 Random即:java.util.Random,ThreadLocalRandom 即: ...

  3. java中多线程中Runnable接口和Thread类介绍

    java中的线程时通过调用操作系统底层的线程来实现线程的功能的. 先看如下代码,并写出输出结果. // 请问输出结果是什么? public static void main(String[] args ...

  4. Java中基础类库使用

    Java中基础类库: 在这里我仅仅介绍几种我个人觉得会常常使用的 1:Object类中的Clone机制仅仅是对对象进行浅层次的克隆,假设须要进行深层次的克隆的话那么就要自己写(详细Clone方法请參考 ...

  5. 沉淀再出发:java中的HashMap、ConcurrentHashMap和Hashtable的认识

    沉淀再出发:java中的HashMap.ConcurrentHashMap和Hashtable的认识 一.前言 很多知识在学习或者使用了之后总是会忘记的,但是如果把这些只是背后的原理理解了,并且记忆下 ...

  6. java中的锁

    java中有哪些锁 这个问题在我看了一遍<java并发编程>后尽然无法回答,说明自己对于锁的概念了解的不够.于是再次翻看了一下书里的内容,突然有点打开脑门的感觉.看来确实是要学习的最好方式 ...

  7. java中的字符串相关知识整理

    字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...

  8. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  9. java中Action层、Service层和Dao层的功能区分

    Action/Service/DAO简介: Action是管理业务(Service)调度和管理跳转的. Service是管理具体的功能的. Action只负责管理,而Service负责实施. DAO只 ...

随机推荐

  1. 万字长文带你入门Zookeeper!!!

    导读 文章首发于微信公众号[码猿技术专栏],原创不易,谢谢支持. Zookeeper 相信大家都听说过,最典型的使用就是作为服务注册中心.今天陈某带大家从零基础入门 Zookeeper,看了本文,你将 ...

  2. 1054 The Dominant Color (20分)(水)

    Behind the scenes in the computer's memory, color is always talked about as a series of 24 bits of i ...

  3. ssh配置文件最佳实践(伪)

    时间:2019-09-11 说明:以下配置是基于常用安全设置,并增加阿里云要求的安全参数而成 版本:第一版 # 1.监听相关 ## 指定ssh端口 Port 1314 ## 只监听网络协议 Addre ...

  4. python 删除三天前的日志.py

    #获取所有文件def file(): for cur_dir, dirs, files in os.walk(r'/学习/接口自动化/BestTest/作业/logs'): # cur_dir(当前路 ...

  5. ThinkPHP中的行为扩展和插件详解

    原理分析 将标签与类之间的对应关系(如'app_init'=>array('Common\Behavior\InitHook')),通过Hook类中import或add方法,加载到Hook类中静 ...

  6. 9.2ArrayList 集合 案例,学生管理系统

    循环的使用 添加学生:while嵌套for,for设置变量,内嵌if更新变量.if语句判断变量值 修改学生:for循环内嵌if,获取循环中的某个值. package day9_ArrayList.AL ...

  7. "多行文本"组件:<multi> —— 快应用组件库H-UI

     <import name="multi" src="../Common/ui/h-ui/text/c_text_multi"></impo ...

  8. GO中的channel使用小结

    go关键字可以用来开启一个goroutine(协程))进行任务处理,而多个任务之间如果需要通信,就需要用到channel了. func testSimple(){ intChan := make(ch ...

  9. 逻辑对象中时间类型 保存时 隐藏bug

    开发功能中的一些逻辑对象中的一些时间 属性,在保存数据库时有一个隐藏的bug,假如 我vo属性定义的就是date 类型,那我定时保存数据库时可能就会出错,eq:假如这个属性隔天要重置一些东西,表中这个 ...

  10. D - Complete Tripartite

    三分图染色 链接:https://codeforces.com/contest/1228/problem/D 三分图染色步骤:First 首先找一个点1作为集合A中的点,再找到与1相连的一个点设为2, ...