SecureRandom线程安全吗? [英] Is SecureRandom thread safe?

查看:708
本文介绍了SecureRandom线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SecureRandom线程安全吗?也就是说,在对其进行初始化之后,是否可以依赖下一个随机数来确保线程安全?检查源代码似乎表明它是正确的,并且此错误报告似乎表明它缺乏作为线程安全的文档是javadoc的问题.有没有人确认它实际上是线程安全的?

Is SecureRandom thread safe? That is, after initializing it, can access to the next random number be relied on to be thread safe? Examining the source code seems to show that it is, and this bug report seems to indicate that its lack of documentation as thread safe is a javadoc issue. Has anyone confirmed that it is in fact thread safe?

推荐答案

是的.它扩展了Random,它总是具有事实线程安全的实现,并且从

Yes, it is. It extends Random, which always had a de facto threadsafe implementation, and, from Java 7, explicitly guarantees threadsafety.

如果许多线程使用单个SecureRandom,则可能存在争用,从而影响性能.另一方面,初始化SecureRandom实例可能相对较慢.共享全局RNG还是为每个线程创建一个新的RNG取决于您的应用程序. ThreadLocalRandom 类可能是用作模式以提供支持SecureRandom的解决方案.

If many threads are using a single SecureRandom, there might be contention that hurts performance. On the other hand, initializing a SecureRandom instance can be relatively slow. Whether it is best to share a global RNG, or to create a new one for each thread will depend on your application. The ThreadLocalRandom class could be used as a pattern to provide a solution that supports SecureRandom.

这篇关于SecureRandom线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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