简体   繁体   中英

ThreadLocalRandom consistency in Fork/Join

My requirement is to initialize a very large int array with unique random ints using Fork/Join framework. It looks like I can use ThreadLocalRandom because java doc says it's ideal to use in a Fork/Join situation. My question is: since each thread in the pool gets its own ThreadLocalRandom instance that is not shared, is there any chance of two threads generating the same random int?

Yes - and the probability would be probably about the same as using only one Random for all the threads.

ThreadLocalRandom is designed to reduce contention and overhead (that could occur if several threads use the same instance), but gives NO GUARANTEE that random numbers sequences will be constitued of unique numbers.

If unicity is a requirement, you have to manually check generated values against all the previously generated ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM