United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
JDK-6633229 : java.lang.Math#random uses broken double checked locking

Details
Type:
Bug
Submit Date:
2007-11-22
Status:
Open
Updated Date:
2013-08-14
Project Name:
JDK
Resolved Date:
Component:
core-libs
OS:
windows_xp
Sub-Component:
java.lang
CPU:
x86
Priority:
P5
Resolution:
Unresolved
Affected Versions:
6
Targeted Versions:
tbd_major

Related Reports
Relates:

Sub Tasks

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
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.
                                     
2007-11-22



Hardware and Software, Engineered to Work Together