JDK 8 RFC 6470700: Math.random() / Math.initRNG() uses "double checked locking"
Brian Burkhalter
brian.burkhalter at oracle.com
Wed Aug 21 23:37:52 UTC 2013
With respect to this issue
http://bugs.sun.com/view_bug.do?bug_id=6470700
the code of concern from java.lang.Math is
701 private static Random randomNumberGenerator;
702
703 private static synchronized Random initRNG() {
704 Random rnd = randomNumberGenerator;
705 return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
706 }
731 public static double random() {
732 Random rnd = randomNumberGenerator;
733 if (rnd == null) rnd = initRNG();
734 return rnd.nextDouble();
735 }
where the class variable "randomNumberGenerator" is not used anywhere else in the class. The complaint is that this is an instance of the broken double-checked locking pattern. While at first glance this might appear to be the case, it does not seem so to me. It looks more like an attempt to avoid calling a synchronized method if "randomNumberGenerator" has already been initialized.
A more typical pattern would be
private static Random randomNumberGenerator;
private static synchronized Random getRNG() {
if (randomNumberGenerator == null) {
randomNumberGenerator = new Random();
}
return randomNumberGenerator;
}
public static double random() {
return getRNG().nextDouble();
}
Comments, please.
Thanks,
Brian
More information about the core-libs-dev
mailing list