首页 技术 正文
技术 2022年11月23日
0 收藏 727 点赞 4,963 浏览 1647 个字

Prefer ThreadLocalRandom over Random

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); }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,993
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845