Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the next method in Random use a compareAndSet?

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?

like image 910
Adowrath Avatar asked Oct 26 '15 15:10

Adowrath


1 Answers

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.

like image 166
Simulant Avatar answered Oct 03 '22 04:10

Simulant