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 - 
 
  1. //Generate a random number b/w 0 and 10. 0 <= R < 10
  2. //Using Math.random()
  3. int r1 = (int)Math.random()*10;
  4. //Using Random
  5. Random rand = new Random();
  6. int r2 = rand.nextInt(10);
  7. //Using ThreadLocalRandom
  8. 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

  1. public static void main(String[] args) {
  2. Map<String, Integer> map = new HashMap<>();
  3. for (int i = 0; i < 10000; i++) {
  4. int nextInt = ThreadLocalRandom.current().nextInt(10);
  5. if (nextInt >= 0) {
  6. String positive = "positive";
  7. Integer current = map.get(positive);
  8. map.put(positive, current == null ? 1 : ++current);
  9. } else {
  10. System.out.println(nextInt);
  11. String positive = "negative";
  12. Integer current = map.get(positive);
  13. map.put(positive, current == null ? 1 : ++current);
  14. }
  15. }
  16. System.out.println(map);
  17.  
  18. }

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. MinHash 原理

    最小哈希原理介绍 MinHash是基于Jaccard Index相似度(海量数据不可行)的算法,一种降维的方法A,B 两个集合:A = {s1, s3, s6, s8, s9}  B = {s3, s ...

  2. iOS9 ReplayKit录制视频

    猴子原创,欢迎转载.转载请注明: 转载自Cocos2Der-CSDN,谢谢! 原文地址: http://blog.csdn.net/cocos2der/article/details/50260873 ...

  3. Redis服务信息

    想要获得下面的redis服务器信息,只需要在命令行中输入:info server 部分记录了 Redis 服务器的信息,它包含以下域: redis_version : Redis 服务器版本 redi ...

  4. nifi1.6.0汉化

    1.1 测试机 l  Apache NiFi 1.6.0 l  HDP 2.6.3 l  集群规模:单节点 l  操作系统:CentOs7 l  以下所有操作均在root用户下执行 1.2 安装环境 ...

  5. python之多继承与__mro__的使用

    1 class Base(object): def text(self): print('------text-----') class A(Base): def text(self): print( ...

  6. PLSQL Developer使用技巧

    本文由liuyk80贡献 ·PL/SQL Developer 使用技巧 1.PL/SQL Developer 记住登陆密码 在使用 PL/SQL Developer 时,为了工作方便希望 PL/SQL ...

  7. struts2.1.8+hibernate2.5.6+spring3.0(ssh2三大框架)常见异常原因和解决方案

    ---------------------------------------------------------------------------------------------------- ...

  8. Java多线程 阻塞队列和并发集合

    转载:大关的博客 Java多线程 阻塞队列和并发集合 本章主要探讨在多线程程序中与集合相关的内容.在多线程程序中,如果使用普通集合往往会造成数据错误,甚至造成程序崩溃.Java为多线程专门提供了特有的 ...

  9. 6.3 Query 语句对系统性能的影响

    我们重点分析实现同样功能的不同SQL 语句在性能方面会产生较大的差异的根本原因,并通过一个较为典型的示例来对我们的分析做出相应的验证. 为什么返回完全相同结果集的不同SQL 语句,在执行性能方面存在差 ...

  10. complex figure

    1/z   ----direct by MATLAB exp(z)    by QT logZ       by  QT 1/z      用QT画的 -----2018-03-17--------- ...