Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how random is Math.random() in java across different jvms or different machines

Tags:

java

random

I have a large distributed program across many different physical servers, each program spawns many threads, each thread use Math.random() in its operations to draw a piece from many common resource pools.

The goal is to utilize the pools evenly across all operations. Sometimes, it doesn't appear so random by looking at a snapshot on a resource pool to see which pieces it's getting at that instant (it might actually be, but it's hard to measure and find out for sure).

Is there something that's better than Math.random() and performs just as good (not much worse at least)?

like image 886
user881480 Avatar asked Apr 01 '12 10:04

user881480


2 Answers

Math.random() is based on java.util.Random, which is based on a linear congruential generator. That means its randomness is not perfect, but good enough for most tasks, and it sounds like it should be sufficient for your task.

However, it sounds like you're using the double return value of Math.random() to choose between a fixed number of choices, which may further degrade the quality of the randomness. It would be better to use java.util.Random.nextInt() - just be sure to reuse the same Random object.

Sometimes, it doesn't appear so random by looking at a snapshot on a resource pool to see which pieces it's getting at that instant

Our brains are really good at spotting patterns in perfect randomness, so that means almost nothing.

like image 141
Michael Borgwardt Avatar answered Nov 15 '22 14:11

Michael Borgwardt


Math.Random's algorithm is "random enough" for any platform. The mathematical model used for creating psuedo-random numbers is a good one. It depends on how many threads you use. For anything but a really large number of threads, this will not give you even distribution (the nature of random numbers), and then Math.random() will give you plenty of overhead.

Try a better option: make a resource pool class, which distributes them evenly - and then just keep it's critical section in the "distribute" method protected.

like image 37
user1304831 Avatar answered Nov 15 '22 14:11

user1304831