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)?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With