6470700: Math.random() / Math.initRNG() uses "double checked locking"
authorbpb
Thu, 22 Aug 2013 13:32:22 -0700
changeset 19583 828d85603705
parent 19582 1cab3f8c48c7
child 19584 6ddcdf868ab5
6470700: Math.random() / Math.initRNG() uses "double checked locking" Summary: Replace class Random variable with a static final holder class Reviewed-by: alanb, mduigou, chegar Contributed-by: Brian Burkhalter <brian.burkhalter@oracle.com>
jdk/src/share/classes/java/lang/Math.java
jdk/src/share/classes/java/lang/StrictMath.java
--- a/jdk/src/share/classes/java/lang/Math.java	Wed Aug 21 17:17:45 2013 +0200
+++ b/jdk/src/share/classes/java/lang/Math.java	Thu Aug 22 13:32:22 2013 -0700
@@ -698,11 +698,8 @@
             return 0;
     }
 
-    private static Random randomNumberGenerator;
-
-    private static synchronized Random initRNG() {
-        Random rnd = randomNumberGenerator;
-        return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
+    private static final class RandomNumberGeneratorHolder {
+        static final Random randomNumberGenerator = new Random();
     }
 
     /**
@@ -729,9 +726,7 @@
      * @see Random#nextDouble()
      */
     public static double random() {
-        Random rnd = randomNumberGenerator;
-        if (rnd == null) rnd = initRNG();
-        return rnd.nextDouble();
+        return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
     }
 
     /**
--- a/jdk/src/share/classes/java/lang/StrictMath.java	Wed Aug 21 17:17:45 2013 +0200
+++ b/jdk/src/share/classes/java/lang/StrictMath.java	Thu Aug 22 13:32:22 2013 -0700
@@ -678,11 +678,8 @@
         return Math.round(a);
     }
 
-    private static Random randomNumberGenerator;
-
-    private static synchronized Random initRNG() {
-        Random rnd = randomNumberGenerator;
-        return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
+    private static final class RandomNumberGeneratorHolder {
+        static final Random randomNumberGenerator = new Random();
     }
 
     /**
@@ -709,9 +706,7 @@
      * @see Random#nextDouble()
      */
     public static double random() {
-        Random rnd = randomNumberGenerator;
-        if (rnd == null) rnd = initRNG();
-        return rnd.nextDouble();
+        return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
     }
 
     /**