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. Zip操作的工具类

     /** * Copyright 2002-2010 the original author is huanghe. */package com.ucap.web.cm.webapp.util; ...

  2. MySql常用操作语句(2:数据库、表管理以及数据操作)

    本文主要内容转自一博文. 另外可供参考资源: SQL语句教程 SQL语法 1.数据库(database)管理  1.1 create 创建数据库 mysql> create database f ...

  3. 细说Android事件传递

    一.View的dispatchTouchEvent和onTouchEvent 探讨Android事件传递机制前,明确android的两大基础控件类型:View和ViewGroup.View即普通的控件 ...

  4. myBatis源码之XMLConfigBuilder

    XMLConfigBuilder是对mybatis的配置文件进行解析的类,会对myabtis解析后的信息存放在Configuration对象中,Configuration对象会贯穿整个mybatis的 ...

  5. 关于C语言程序条件编译的简单使用方法

    #include <stdio.h> #include <stdlib.h> #define Mode //如果定义了Mode,那么就执行这个函数 #ifdef Mode vo ...

  6. 如何在linux上构建objective-c程序

    swfit目前还是os x独占,以后会不会扩展到其他系统还未可知,但objective-c并不只存在于os x,在linux下gcc和clang都支持obj-c哦,下面简单把如何在ubuntu上构建o ...

  7. 使用vs2010 opencv2.4.4编译release版本程序

    大体上要注意一下几点内容: 1.vc++目录的选择上,库目录选择为opencv目录中的staticlib目录 2.在链接->输入->附加依赖库,中添加,相应的staticlib库目录中的所 ...

  8. HttpWebRequest类库注意事项以及常见问题

    ServicePoint: 提供HTTP连接的连接管理ServicePointManager: 管理ServicePoint 对象的集合 注意事项:1. 将http的request的keepAlive ...

  9. ionic1 打包过程 常用命令行

    ionic start myapp                                             myapp是项目名字 ionic start myapp --v2     ...

  10. Django(二)如何在IIS中部署django项目

    环境配置 windows7 Django 2.0 python 3.6 wfastcgi 3.0 关键步骤 打开CGI功能 控制面板/程序和功能/打开或关闭windwos功能,如图: 安装wfastc ...