ThreadLocalRandom如何减少争用? [英] How does ThreadLocalRandom results in less Contention?

查看:166
本文介绍了ThreadLocalRandom如何减少争用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在浏览Java 7的新功能并发现添加了这个新类:

Was going through Java 7 new features and found this new class added:


对于并发访问,使用ThreadLocalRandom而不是
Math.random()会减少争用,最终会产生更好的
表现。

For concurrent access, using ThreadLocalRandom instead of Math.random() results in less contention and, ultimately, better performance.

正在研究如何实施导致较少的争用和更好的性能。

Was researcing how this is implemented resulting in less Contention and better performance.

推荐答案

实际上,两者之间的区别在于同步。 Math#random()可能同时由多个线程调用,因此必须同步,而 ThreadLocalRandom 是一个不同步的版本随机是线程绑定意味着每个线程都有自己的(更快)分配。

Effectively, the difference between the two is synchronization. Math#random() may be called by multiple threads simultaneously thus having to synchronize, while ThreadLocalRandom is an unsynchronized version of Random that is thread bound meaning each thread gets its own (faster) allocation.

如果你仔细看看在实现中,你会发现 Math#random()使用单个 java.util.Random 的实例生成随机数,其中 ThreadLocalRandom 为每个线程分配一个实例,从而消除了这种意义上的争用。

If you take a closer look at the implementation, you will find out that Math#random() uses a single instance of java.util.Random to generate random numbers, where ThreadLocalRandom allocates an instance per thread thus eliminating contention in that sense.

ThreadLocalRandom 实现并发其中 Math#random()实现同步

这篇关于ThreadLocalRandom如何减少争用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆