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 onjava.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
doublereturn value ofMath.random()to choose between a fixed number of choices, which may further degrade the quality of the randomness. It would be better to usejava.util.Random.nextInt()– just be sure to reuse the sameRandomobject.Our brains are really good at spotting patterns in perfect randomness, so that means almost nothing.