Is Random class thread safe?

前端 未结 8 926
臣服心动
臣服心动 2020-12-13 11:53

Is it valid to share one instance of the Random class between multiple threads? And to call nextInt(int) from multiple threads in particular?

8条回答
  •  有刺的猬
    2020-12-13 12:12

    As said, it is thread save, but it may be wise to use java.util.concurrent.ThreadLocalRandom according to this article (link dead). ThreadLocalRandom is also a subclass of Random, so it is backwards compatible.

    The article linked compared profiling results of the different Random classes: java.util.Random, java.util.concurrent.ThreadLocalRandom and java.lang.ThreadLocal. The results showed, that the usage of ThreadLocalRandom is most performant, followed by ThreadLocal and worst performing Random itself.

提交回复
热议问题