Removing a layer of synchronization on Math.random

Rémi Forax forax at univ-mlv.fr
Sun Jun 6 09:59:24 UTC 2010


Le 06/06/2010 00:45, Martin Buchholz a écrit :
> Thanks to all the reviewers who were too polite to say:
>
> """What was Martin thinking?"""
>
> For some reason I had imagined that Math.random()
> was itself synchronized.
>
> After editing, I have a very small change that is hardly worth doing
> except that I already have a webrev.
>
> http://cr.openjdk.java.net/~martin/webrevs/openjdk7/Math.random/
>
> Martin
>    

I think initRG can be written like that:

  private static synchronized Random initRNG() {
    RandomrandomNumberGenerator = this.randomNumberGenerator;
    return (randomNumberGenerator == null)? this.randomNumberGenerator = new Random() :randomNumberGenerator;
  }


Rémi

> On Sat, Jun 5, 2010 at 07:00, Eamonn McManus<Eamonn.McManus at sun.com>  wrote:
>    
>> It seems to me that if two threads call this Math.random() at the same time
>> then two instances of Random() can be constructed. That contradicts the
>> specification of the method, and is theoretically observable because the two
>> values from Math.random() will typically not be a pair of values that could
>> have been returned from consecutive calls to nextDouble() on a single Random
>> instance. Granted, the chances of this actually mattering are infinitesimal,
>> but I think the performance gain of avoiding a synchronized method only on
>> the very first call to Math.random() is infinitesimal too. So I'd be
>> inclined to leave well enough alone here.
>> Eamonn
>>
>> Martin Buchholz wrote:
>>      
>>> Here's an optimization for Math.random() that appears to be safe,
>>> despite the double-check access:
>>>
>>> http://cr.openjdk.java.net/~martin/webrevs/openjdk7/Math.random/
>>>
>>> David, if you agree, could you file a bug?
>>>
>>> Thanks,
>>>
>>> Martin
>>>
>>>        
>>      

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/core-libs-dev/attachments/20100606/a1d99192/attachment.html>


More information about the core-libs-dev mailing list