Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seed a random generator without time in java cross-plateform-ably

Tags:

java

random

I'm initializing two random number generators on two threads almost simultaneously and I want the two generators behaves completely different. I will call Random.nextInt(7) on two generators one right after another very often. Using System.currentTimeMillis() is not a good idea because it looks like my computer is so fast that there's a large chance that the number I get from the two generators are the same. So is there any way to config the Random so that though they are called one right after another, they still behave differently? I want the solution to be cross-platform compatible so any platform-specific idea such as read from /dev/random is not acceptable. Thanks for help.

like image 543
YankeeWhiskey Avatar asked Feb 11 '13 01:02

YankeeWhiskey


Video Answer


1 Answers

One way: Seed each Random instance with a UUID (GUID) converted (hashed? but probably not just a cast) to a long.

  • Generate UUID in Java

Other answers suggest using nanoTime, which may be suitable depending on the speed of the hardware, but I prefer the UUID route.

like image 179
Mitch Wheat Avatar answered Oct 05 '22 18:10

Mitch Wheat