2 years ago

#64680

test-img

Challe

How does java.util.Random guarantee thread safety on the nextGaussian method?

According to the Java documentation the nextGaussian mehtod is implemented as:

 private double nextNextGaussian;
 private boolean haveNextNextGaussian = false;

 public double nextGaussian() {
   if (haveNextNextGaussian) {
     haveNextNextGaussian = false;
     return nextNextGaussian;
   } else {
     double v1, v2, s;
     do {
       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
       s = v1 * v1 + v2 * v2;
     } while (s >= 1 || s == 0);
     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
     nextNextGaussian = v2 * multiplier;
     haveNextNextGaussian = true;
     return v1 * multiplier;
   }
 }

How can it be guaranteed to be thread safe when the haveNextNextGaussian isn't atomic? Wouldn't it be possible for 2 threads to call the function at the same time so that both threads read haveNextNextGaussian as true and then both would set it to false and effectively returning the same value on both threads?

java

random

thread-safety

0 Answers

Your Answer

Accepted video resources