While reading through the documentation for the java.util.Random class in Java, I stumbled upon something inside the next
method that I couldn't quite get my head around.
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
I noticed the use of !seed.compareAndSet(oldseed, nextseed)
, and I'm trying to understand what it's there for. What is the explanation?
From JavaDoc for compareAndSet:
Atomically sets the value to the given updated value if the current value == the expected value.
This is done to make sure that between the seed.get()
and the set (inside the comapreAndSet), no other thread has called another set()
(e.g. by a parallel call of next()
). Because the old seed is used to calculate the next seed. If in between an other Thread would have called the seed.set()
method the "next" seed would not be calculated with the latest value. The value before the last value would have been used and the algorithem would have side effects in a multi threaded environment.
This algorithm is used to be thread save. Because if the old value is not the expected one, the loop will be repeated until both values match.
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