JDK-6633229 : java.lang.Math#random uses broken double checked locking
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6
  • Priority: P5
  • Status: Resolved
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-11-22
  • Updated: 2013-08-22
  • Resolved: 2013-08-22
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_02"
Java(TM) SE Runtime Environment (build 1.6.0_02-b06)
Java HotSpot(TM) Client VM (build 1.6.0_02-b06, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [Version 5.1.2600]

A DESCRIPTION OF THE PROBLEM :
Method java.lang.Math#random uses the broken double check locking pattern. More information can be found on http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.

Using this pattern may lead to unpredictable results in a contended environment.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
This is very hard to reproduce, if the bug is triggered in current JVMs at all. Specialized and future JVMs may suffer as the amount of processors and threads per processor grows.

Possibly a duplicate of 6470700.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Not applicable.
ACTUAL -
Not applicable.

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Not applicable.

REPRODUCIBILITY :
This bug can be reproduced rarely.

---------- BEGIN SOURCE ----------
Not applicable.
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
There is no workaround.

A fix is easy. Either statically initialize field randomNumberGenerator, or make method random synchronized.

Comments
Duplicates JDK-6470700.
22-08-2013

EVALUATION This is not an ordinary use of double-checked locking, because Random is a thread-safe class. I believe there is no way that data corruption can be observed, even in theory. E.g. There is no way that a NullPointerException can be observed. The only bug I see is when multiple threads race to initialize the randomNumberGenerator field. Multiple threads may create and use a new Random, which is technically a violation of the spec, but it is very hard to observe any effect of this defect. If two threads call Math.random() at almost exactly the same time, there is a greater than usual risk that they will get the same seed (initialized from System.nanoTime()), which might not be random enough for some users.
22-11-2007