From ff7c51cd184ccf7c61561554eaaab800bf461fb9 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Thu, 22 Aug 2013 13:32:22 -0700 Subject: [PATCH] 6470700: Math.random() / Math.initRNG() uses "double checked locking" Replace class Random variable with a static final holder class Reviewed-by: alanb, mduigou, chegar --- jdk/src/share/classes/java/lang/Math.java | 11 +++-------- jdk/src/share/classes/java/lang/StrictMath.java | 11 +++-------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/jdk/src/share/classes/java/lang/Math.java b/jdk/src/share/classes/java/lang/Math.java index 23bc934688d..ae83e4265ad 100644 --- a/jdk/src/share/classes/java/lang/Math.java +++ b/jdk/src/share/classes/java/lang/Math.java @@ -698,11 +698,8 @@ public final class Math { 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 @@ public final class Math { * @see Random#nextDouble() */ public static double random() { - Random rnd = randomNumberGenerator; - if (rnd == null) rnd = initRNG(); - return rnd.nextDouble(); + return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); } /** diff --git a/jdk/src/share/classes/java/lang/StrictMath.java b/jdk/src/share/classes/java/lang/StrictMath.java index eb202d53202..52336484e75 100644 --- a/jdk/src/share/classes/java/lang/StrictMath.java +++ b/jdk/src/share/classes/java/lang/StrictMath.java @@ -678,11 +678,8 @@ public final class StrictMath { 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 @@ public final class StrictMath { * @see Random#nextDouble() */ public static double random() { - Random rnd = randomNumberGenerator; - if (rnd == null) rnd = initRNG(); - return rnd.nextDouble(); + return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); } /**