Java 7 has introduced a new random number generator - ThreadLocalRandom

Normally to generate Random numbers, we either do

However in a concurrent applications usage of above leads to contention issues -

  • Random is thread safe for use by multiple threads. But if multiple threads use the same instance of Random, the same seed is shared by multiple threads. It leads to contention between multiple threads and so to performance degradation.
ThreadLocalRandom is solution to above problem. ThreadLocalRandom has a Random instance per thread and safeguards against contention.
 
From the api docs - 

Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is IntLong, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.

Usage Example - 
 
//Generate a random number b/w 0 and 10.  0 <= R < 10
//Using Math.random()
int r1 = (int)Math.random()*10;
//Using Random
Random rand = new Random();
int r2 = rand.nextInt(10);
//Using ThreadLocalRandom
int r3 = ThreadLocalRandom.current().nextInt(10);

http://thoughtfuljava.blogspot.com/2012/09/prefer-threadlocalrandom-over-random.html

http://www.blogjava.net/yongboy/archive/2012/02/04/369574.html

    public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
int nextInt = ThreadLocalRandom.current().nextInt(10);
if (nextInt >= 0) {
String positive = "positive";
Integer current = map.get(positive);
map.put(positive, current == null ? 1 : ++current);
} else {
System.out.println(nextInt);
String positive = "negative";
Integer current = map.get(positive);
map.put(positive, current == null ? 1 : ++current);
}
}
System.out.println(map); }

Prefer ThreadLocalRandom over Random的更多相关文章

  1. ThreadLocalRandom ---- 提升Random在大并发下的效率

    本博客系列是学习并发编程过程中的记录总结.由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅. 并发编程系列博客传送门 随机数 随机数在科学研究与工程实际中有着极其重要的应用! ...

  2. 为什么要使用ThreadLocalRandom代替Random生成随机数

    799 java里有伪随机型和安全型两种随机数生成器,伪随机生成器根据特定公式将seed转换成新的伪随机数据的一部分,安全随机生成器在底层依赖到操作系统提供的随机事件来生成数据. 安全随机生成器 需要 ...

  3. Random类、ThreadLocalRandom类

    Random和ThreadLocalRandom类均用于生成伪随机数. Random的构造函数: Random()     默认以系统当前时间为种子,相当于Random(System.currentT ...

  4. Math&Random&ThreadLocalRandom类

    Math类 //绝对值值运算: Math.abs(18.999); //返回19.999这个数的绝对值 Math.abs(-12.58); // 返回-12.58这个数的绝对值,为12.58 //取值 ...

  5. JUC源码分析-其它工具类(一)ThreadLocalRandom

    JUC源码分析-其它工具类(一)ThreadLocalRandom ThreadLocalRandom 是 JDK7 在 JUC 包下新增的随机数生成器,它解决了 Random 在多线程下多个线程竞争 ...

  6. 【8-22】java学习笔记04

    java基础类库 Scanner类(java.util.scanner) Scanner对象.hasNextXxx(),hasNext()默认方法为字符串://Returns true if this ...

  7. 解密随机数生成器(二)——从java源码看线性同余算法

    Random Java中的Random类生成的是伪随机数,使用的是48-bit的种子,然后调用一个linear congruential formula线性同余方程(Donald Knuth的编程艺术 ...

  8. Java中基础类库使用

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

  9. 常用 API

    运行 Java 程序的参数.使用 Scanner 获取键盘输入.使用 BufferedReader 获取键盘输入.System类.Runtime类.Object类.Java 7新增的 Objects ...

随机推荐

  1. RedHat系列软件管理(第二版) --源码包安装

    RedHat系列软件管理 --源码包安装 源码包特点: 拥有广泛的平台支持性,可以装在所有的类UNIX操作系统上,不用考虑CPU架构. 灵活性,可以在安装过程中指定特有的选项. 定制度非常高,可以自己 ...

  2. Linux文件与目录管理 - ls, cp, mv

    [root@www ~]# ls [-aAdfFhilnrRSt] 目录名称 [root@www ~]# ls [--color={never,auto,always}] 目录名称 [root@www ...

  3. JSP 知识基本

    from:http://blog.csdn.net/caipeichao2/article/details/38589293 more:http://www.2cto.com/kf/web/jsp/4 ...

  4. gradle构建android项目详解

    1.用Gradle构建 1.1 工程结构 如图所示,这是一个不能更普通的Android的Gradle工程了. 根目录下面的settings.gradle当中主要是用来include子模块的,比如我们这 ...

  5. unix下各种查看“变量”的命令比较

    子程序只会继承父程序的环境变量,而不继承其自定义变量. env 查看所有环境变量 set 查看所有变量,包括环境变量和自定义变量 set 还可以给程序位置参数赋值: set 1 2 3 将1赋值给$1 ...

  6. LeetCode(29)-Plus One

    题目: Given a non-negative number represented as an array of digits, plus one to the number. The digit ...

  7. spring boot之入门配置(一)

    yml.properties配置文件 yml相比properties配置文件,yml可以省略不必要的前缀,并且看起来更加的有层次感.推荐使用yml文件. @Value 根据配置文件的配置项获取对应的v ...

  8. AOP的相关概念

  9. log4j日志的配置

    在项目开发中,记录错误日志方便调试.便于发现系统运行过程中的错误.便于后期分析, 在java中,记录日志有很多种方式,比如说log4j log4j需要导入的包: commons-loggin.jar ...

  10. JVM-GC工作原理

     配置Garbage Collection 2012-09-17 14:53:18 分类: Java   上面这幅图是我从网络上摘到的,它展现了在一个的理想系统的模型下GC对系统的影响.图的最顶上红色 ...