我应该使用java.util.Random的全局实例,还是每次使用时都构造一个全局实例? [英] java - Should I use a global instance of java.util.Random, or construct one everytime it is used?

查看:244
本文介绍了我应该使用java.util.Random的全局实例,还是每次使用时都构造一个全局实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎总结了一下.我已经看到人们在全局范围内构造一个Random实例,并在所有代码中使用它,并且我也看到人们每次想要使用Random时都构造一个实例.

The title pretty much sums it up. I have seen people construct an instance of Random globally, and use it in all of their code, and I have also seen people that construct an instance everytime they want to use Random.

我的问题是:我应该何时构建一个新的Random实例来生成随机数?

My question is: When, if ever, should I construct a new instance of Random for generating random numbers?

Math.random()将Random实例存储在RandomNumberGeneratorHolder中,并在每次调用Math.random()时调用它.

Math.random() stores a Random instance in a RandomNumberGeneratorHolder, and calls it every time Math.random() is called.

我的观点:我应该使用全局Random()实例,因为:

My view: I should use a global Random() instance, because:

  1. 节省创建对象的时间. Random()的无参数构造函数调用seedUniquifier(),该方法基本上一直循环直到找到新的AtomicLong(),并将其提升为System.nanoTime()的能力.很贵.
  2. 我目前正在将随机数字用于自定义hashCode().我重写了equals(),现在我对hashCode()做同样的事情.我正在执行此操作的类将主要用于将数据存储在Collections中,这会严重滥用hashCode().看到无参数的Random()构造函数比我用来生成哈希码的几次乘法要花更多的时间,它将使执行时间增加一倍以上.不好.

我想不出任何其他原因,但是如果我应该使用全局Random实例,我可以想象Java开发人员除了特殊情况的构造函数外,还使用at实例字段实现Random.那告诉我我错了.我应该使用全局随机实例吗?

I can't think of any more reasons, but if I should use a global Random instance, I can imagine java developers implementing Random with at instance field, in addition to the constructor for special cases. That tells me that I am wrong. Should I use a global Random instance?

推荐答案

出于性能原因,您应该使用全局Random实例,而不是每次都初始化一个实例-另请参见

You should use a global Random instance for performance reasons, instead of initializing one each time - see also API.

请注意:

  • for multi-threaded applications, you should use a ThreadLocalRandom instead, in the form of ThreadLocalRandom.current().next... for each call (see official recommendation on the matter).
  • for cryptographically secure random numbers, use a SecureRandom instead.

这篇关于我应该使用java.util.Random的全局实例,还是每次使用时都构造一个全局实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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