src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java
branchJDK-8193209-branch
changeset 59086 214afc7a1e02
parent 58138 1e4270f875ee
equal deleted inserted replaced
59085:c660730af328 59086:214afc7a1e02
    29  * file:
    29  * file:
    30  *
    30  *
    31  * Written by Doug Lea with assistance from members of JCP JSR-166
    31  * Written by Doug Lea with assistance from members of JCP JSR-166
    32  * Expert Group and released to the public domain, as explained at
    32  * Expert Group and released to the public domain, as explained at
    33  * http://creativecommons.org/publicdomain/zero/1.0/
    33  * http://creativecommons.org/publicdomain/zero/1.0/
       
    34  *
       
    35  * Additional modifications by Guy Steele in 2019 to refactor the code
       
    36  * and to implement the {@link RandomGenerator} interface.
    34  */
    37  */
    35 
    38 
    36 package java.util.concurrent;
    39 package java.util.concurrent;
    37 
    40 
    38 import java.io.ObjectStreamField;
    41 import java.io.ObjectStreamField;
    39 import java.security.AccessControlContext;
    42 import java.security.AccessControlContext;
    40 import java.util.Random;
    43 import java.util.Random;
    41 import java.util.Spliterator;
    44 import java.util.Spliterator;
    42 import java.util.concurrent.atomic.AtomicInteger;
    45 import java.util.concurrent.atomic.AtomicInteger;
    43 import java.util.concurrent.atomic.AtomicLong;
    46 import java.util.concurrent.atomic.AtomicLong;
    44 import java.util.function.DoubleConsumer;
    47 import java.util.random.RandomSupport;
    45 import java.util.function.IntConsumer;
       
    46 import java.util.function.LongConsumer;
       
    47 import java.util.stream.DoubleStream;
       
    48 import java.util.stream.IntStream;
       
    49 import java.util.stream.LongStream;
       
    50 import java.util.stream.StreamSupport;
       
    51 import jdk.internal.misc.Unsafe;
    48 import jdk.internal.misc.Unsafe;
    52 import jdk.internal.misc.VM;
    49 import jdk.internal.misc.VM;
    53 
    50 
    54 /**
    51 /**
    55  * A random number generator isolated to the current thread.  Like the
    52  * A random number generator isolated to the current thread.  Like the
   121      *
   118      *
   122      * Implementations of non-core methods are mostly the same as in
   119      * Implementations of non-core methods are mostly the same as in
   123      * SplittableRandom, that were in part derived from a previous
   120      * SplittableRandom, that were in part derived from a previous
   124      * version of this class.
   121      * version of this class.
   125      *
   122      *
   126      * The nextLocalGaussian ThreadLocal supports the very rarely used
   123      * This implementation of ThreadLocalRandom overrides the
   127      * nextGaussian method by providing a holder for the second of a
   124      * definition of the nextGaussian() method in the class Random,
   128      * pair of them. As is true for the base class version of this
   125      * and instead uses the ziggurat-based algorithm that is the
   129      * method, this time/space tradeoff is probably never worthwhile,
   126      * default for the RandomGenerator interface.
   130      * but we provide identical statistical properties.
   127      */
   131      */
       
   132 
       
   133     private static long mix64(long z) {
       
   134         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
       
   135         z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
       
   136         return z ^ (z >>> 33);
       
   137     }
       
   138 
   128 
   139     private static int mix32(long z) {
   129     private static int mix32(long z) {
   140         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
   130         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
   141         return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
   131         return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
   142     }
   132     }
   160      * rely on (static) atomic generators to initialize the values.
   150      * rely on (static) atomic generators to initialize the values.
   161      */
   151      */
   162     static final void localInit() {
   152     static final void localInit() {
   163         int p = probeGenerator.addAndGet(PROBE_INCREMENT);
   153         int p = probeGenerator.addAndGet(PROBE_INCREMENT);
   164         int probe = (p == 0) ? 1 : p; // skip 0
   154         int probe = (p == 0) ? 1 : p; // skip 0
   165         long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
   155         long seed = RandomSupport.mixMurmur64(seeder.getAndAdd(SEEDER_INCREMENT));
   166         Thread t = Thread.currentThread();
   156         Thread t = Thread.currentThread();
   167         U.putLong(t, SEED, seed);
   157         U.putLong(t, SEED, seed);
   168         U.putInt(t, PROBE, probe);
   158         U.putInt(t, PROBE, probe);
   169     }
   159     }
   170 
   160 
   210     protected int next(int bits) {
   200     protected int next(int bits) {
   211         return nextInt() >>> (32 - bits);
   201         return nextInt() >>> (32 - bits);
   212     }
   202     }
   213 
   203 
   214     /**
   204     /**
   215      * The form of nextLong used by LongStream Spliterators.  If
       
   216      * origin is greater than bound, acts as unbounded form of
       
   217      * nextLong, else as bounded form.
       
   218      *
       
   219      * @param origin the least value, unless greater than bound
       
   220      * @param bound the upper bound (exclusive), must not equal origin
       
   221      * @return a pseudorandom value
       
   222      */
       
   223     final long internalNextLong(long origin, long bound) {
       
   224         long r = mix64(nextSeed());
       
   225         if (origin < bound) {
       
   226             long n = bound - origin, m = n - 1;
       
   227             if ((n & m) == 0L)  // power of two
       
   228                 r = (r & m) + origin;
       
   229             else if (n > 0L) {  // reject over-represented candidates
       
   230                 for (long u = r >>> 1;            // ensure nonnegative
       
   231                      u + m - (r = u % n) < 0L;    // rejection check
       
   232                      u = mix64(nextSeed()) >>> 1) // retry
       
   233                     ;
       
   234                 r += origin;
       
   235             }
       
   236             else {              // range not representable as long
       
   237                 while (r < origin || r >= bound)
       
   238                     r = mix64(nextSeed());
       
   239             }
       
   240         }
       
   241         return r;
       
   242     }
       
   243 
       
   244     /**
       
   245      * The form of nextInt used by IntStream Spliterators.
       
   246      * Exactly the same as long version, except for types.
       
   247      *
       
   248      * @param origin the least value, unless greater than bound
       
   249      * @param bound the upper bound (exclusive), must not equal origin
       
   250      * @return a pseudorandom value
       
   251      */
       
   252     final int internalNextInt(int origin, int bound) {
       
   253         int r = mix32(nextSeed());
       
   254         if (origin < bound) {
       
   255             int n = bound - origin, m = n - 1;
       
   256             if ((n & m) == 0)
       
   257                 r = (r & m) + origin;
       
   258             else if (n > 0) {
       
   259                 for (int u = r >>> 1;
       
   260                      u + m - (r = u % n) < 0;
       
   261                      u = mix32(nextSeed()) >>> 1)
       
   262                     ;
       
   263                 r += origin;
       
   264             }
       
   265             else {
       
   266                 while (r < origin || r >= bound)
       
   267                     r = mix32(nextSeed());
       
   268             }
       
   269         }
       
   270         return r;
       
   271     }
       
   272 
       
   273     /**
       
   274      * The form of nextDouble used by DoubleStream Spliterators.
       
   275      *
       
   276      * @param origin the least value, unless greater than bound
       
   277      * @param bound the upper bound (exclusive), must not equal origin
       
   278      * @return a pseudorandom value
       
   279      */
       
   280     final double internalNextDouble(double origin, double bound) {
       
   281         double r = (nextLong() >>> 11) * DOUBLE_UNIT;
       
   282         if (origin < bound) {
       
   283             r = r * (bound - origin) + origin;
       
   284             if (r >= bound) // correct for rounding
       
   285                 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
       
   286         }
       
   287         return r;
       
   288     }
       
   289 
       
   290     /**
       
   291      * Returns a pseudorandom {@code int} value.
   205      * Returns a pseudorandom {@code int} value.
   292      *
   206      *
   293      * @return a pseudorandom {@code int} value
   207      * @return a pseudorandom {@code int} value
   294      */
   208      */
   295     public int nextInt() {
   209     public int nextInt() {
   296         return mix32(nextSeed());
   210         return mix32(nextSeed());
   297     }
   211     }
   298 
   212 
   299     /**
   213     /**
   300      * Returns a pseudorandom {@code int} value between zero (inclusive)
       
   301      * and the specified bound (exclusive).
       
   302      *
       
   303      * @param bound the upper bound (exclusive).  Must be positive.
       
   304      * @return a pseudorandom {@code int} value between zero
       
   305      *         (inclusive) and the bound (exclusive)
       
   306      * @throws IllegalArgumentException if {@code bound} is not positive
       
   307      */
       
   308     public int nextInt(int bound) {
       
   309         if (bound <= 0)
       
   310             throw new IllegalArgumentException(BAD_BOUND);
       
   311         int r = mix32(nextSeed());
       
   312         int m = bound - 1;
       
   313         if ((bound & m) == 0) // power of two
       
   314             r &= m;
       
   315         else { // reject over-represented candidates
       
   316             for (int u = r >>> 1;
       
   317                  u + m - (r = u % bound) < 0;
       
   318                  u = mix32(nextSeed()) >>> 1)
       
   319                 ;
       
   320         }
       
   321         return r;
       
   322     }
       
   323 
       
   324     /**
       
   325      * Returns a pseudorandom {@code int} value between the specified
       
   326      * origin (inclusive) and the specified bound (exclusive).
       
   327      *
       
   328      * @param origin the least value returned
       
   329      * @param bound the upper bound (exclusive)
       
   330      * @return a pseudorandom {@code int} value between the origin
       
   331      *         (inclusive) and the bound (exclusive)
       
   332      * @throws IllegalArgumentException if {@code origin} is greater than
       
   333      *         or equal to {@code bound}
       
   334      */
       
   335     public int nextInt(int origin, int bound) {
       
   336         if (origin >= bound)
       
   337             throw new IllegalArgumentException(BAD_RANGE);
       
   338         return internalNextInt(origin, bound);
       
   339     }
       
   340 
       
   341     /**
       
   342      * Returns a pseudorandom {@code long} value.
   214      * Returns a pseudorandom {@code long} value.
   343      *
   215      *
   344      * @return a pseudorandom {@code long} value
   216      * @return a pseudorandom {@code long} value
   345      */
   217      */
   346     public long nextLong() {
   218     public long nextLong() {
   347         return mix64(nextSeed());
   219         return RandomSupport.mixMurmur64(nextSeed());
   348     }
   220     }
   349 
       
   350     /**
       
   351      * Returns a pseudorandom {@code long} value between zero (inclusive)
       
   352      * and the specified bound (exclusive).
       
   353      *
       
   354      * @param bound the upper bound (exclusive).  Must be positive.
       
   355      * @return a pseudorandom {@code long} value between zero
       
   356      *         (inclusive) and the bound (exclusive)
       
   357      * @throws IllegalArgumentException if {@code bound} is not positive
       
   358      */
       
   359     public long nextLong(long bound) {
       
   360         if (bound <= 0)
       
   361             throw new IllegalArgumentException(BAD_BOUND);
       
   362         long r = mix64(nextSeed());
       
   363         long m = bound - 1;
       
   364         if ((bound & m) == 0L) // power of two
       
   365             r &= m;
       
   366         else { // reject over-represented candidates
       
   367             for (long u = r >>> 1;
       
   368                  u + m - (r = u % bound) < 0L;
       
   369                  u = mix64(nextSeed()) >>> 1)
       
   370                 ;
       
   371         }
       
   372         return r;
       
   373     }
       
   374 
       
   375     /**
       
   376      * Returns a pseudorandom {@code long} value between the specified
       
   377      * origin (inclusive) and the specified bound (exclusive).
       
   378      *
       
   379      * @param origin the least value returned
       
   380      * @param bound the upper bound (exclusive)
       
   381      * @return a pseudorandom {@code long} value between the origin
       
   382      *         (inclusive) and the bound (exclusive)
       
   383      * @throws IllegalArgumentException if {@code origin} is greater than
       
   384      *         or equal to {@code bound}
       
   385      */
       
   386     public long nextLong(long origin, long bound) {
       
   387         if (origin >= bound)
       
   388             throw new IllegalArgumentException(BAD_RANGE);
       
   389         return internalNextLong(origin, bound);
       
   390     }
       
   391 
       
   392     /**
       
   393      * Returns a pseudorandom {@code double} value between zero
       
   394      * (inclusive) and one (exclusive).
       
   395      *
       
   396      * @return a pseudorandom {@code double} value between zero
       
   397      *         (inclusive) and one (exclusive)
       
   398      */
       
   399     public double nextDouble() {
       
   400         return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
       
   401     }
       
   402 
       
   403     /**
       
   404      * Returns a pseudorandom {@code double} value between 0.0
       
   405      * (inclusive) and the specified bound (exclusive).
       
   406      *
       
   407      * @param bound the upper bound (exclusive).  Must be positive.
       
   408      * @return a pseudorandom {@code double} value between zero
       
   409      *         (inclusive) and the bound (exclusive)
       
   410      * @throws IllegalArgumentException if {@code bound} is not positive
       
   411      */
       
   412     public double nextDouble(double bound) {
       
   413         if (!(bound > 0.0))
       
   414             throw new IllegalArgumentException(BAD_BOUND);
       
   415         double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
       
   416         return (result < bound) ? result : // correct for rounding
       
   417             Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
       
   418     }
       
   419 
       
   420     /**
       
   421      * Returns a pseudorandom {@code double} value between the specified
       
   422      * origin (inclusive) and bound (exclusive).
       
   423      *
       
   424      * @param origin the least value returned
       
   425      * @param bound the upper bound (exclusive)
       
   426      * @return a pseudorandom {@code double} value between the origin
       
   427      *         (inclusive) and the bound (exclusive)
       
   428      * @throws IllegalArgumentException if {@code origin} is greater than
       
   429      *         or equal to {@code bound}
       
   430      */
       
   431     public double nextDouble(double origin, double bound) {
       
   432         if (!(origin < bound))
       
   433             throw new IllegalArgumentException(BAD_RANGE);
       
   434         return internalNextDouble(origin, bound);
       
   435     }
       
   436 
       
   437     /**
       
   438      * Returns a pseudorandom {@code boolean} value.
       
   439      *
       
   440      * @return a pseudorandom {@code boolean} value
       
   441      */
       
   442     public boolean nextBoolean() {
       
   443         return mix32(nextSeed()) < 0;
       
   444     }
       
   445 
       
   446     /**
       
   447      * Returns a pseudorandom {@code float} value between zero
       
   448      * (inclusive) and one (exclusive).
       
   449      *
       
   450      * @return a pseudorandom {@code float} value between zero
       
   451      *         (inclusive) and one (exclusive)
       
   452      */
       
   453     public float nextFloat() {
       
   454         return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
       
   455     }
       
   456 
       
   457     public double nextGaussian() {
       
   458         // Use nextLocalGaussian instead of nextGaussian field
       
   459         Double d = nextLocalGaussian.get();
       
   460         if (d != null) {
       
   461             nextLocalGaussian.set(null);
       
   462             return d.doubleValue();
       
   463         }
       
   464         double v1, v2, s;
       
   465         do {
       
   466             v1 = 2 * nextDouble() - 1; // between -1 and 1
       
   467             v2 = 2 * nextDouble() - 1; // between -1 and 1
       
   468             s = v1 * v1 + v2 * v2;
       
   469         } while (s >= 1 || s == 0);
       
   470         double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
       
   471         nextLocalGaussian.set(Double.valueOf(v2 * multiplier));
       
   472         return v1 * multiplier;
       
   473     }
       
   474 
       
   475     // stream methods, coded in a way intended to better isolate for
       
   476     // maintenance purposes the small differences across forms.
       
   477 
       
   478     /**
       
   479      * Returns a stream producing the given {@code streamSize} number of
       
   480      * pseudorandom {@code int} values.
       
   481      *
       
   482      * @param streamSize the number of values to generate
       
   483      * @return a stream of pseudorandom {@code int} values
       
   484      * @throws IllegalArgumentException if {@code streamSize} is
       
   485      *         less than zero
       
   486      * @since 1.8
       
   487      */
       
   488     public IntStream ints(long streamSize) {
       
   489         if (streamSize < 0L)
       
   490             throw new IllegalArgumentException(BAD_SIZE);
       
   491         return StreamSupport.intStream
       
   492             (new RandomIntsSpliterator
       
   493              (0L, streamSize, Integer.MAX_VALUE, 0),
       
   494              false);
       
   495     }
       
   496 
       
   497     /**
       
   498      * Returns an effectively unlimited stream of pseudorandom {@code int}
       
   499      * values.
       
   500      *
       
   501      * @implNote This method is implemented to be equivalent to {@code
       
   502      * ints(Long.MAX_VALUE)}.
       
   503      *
       
   504      * @return a stream of pseudorandom {@code int} values
       
   505      * @since 1.8
       
   506      */
       
   507     public IntStream ints() {
       
   508         return StreamSupport.intStream
       
   509             (new RandomIntsSpliterator
       
   510              (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
       
   511              false);
       
   512     }
       
   513 
       
   514     /**
       
   515      * Returns a stream producing the given {@code streamSize} number
       
   516      * of pseudorandom {@code int} values, each conforming to the given
       
   517      * origin (inclusive) and bound (exclusive).
       
   518      *
       
   519      * @param streamSize the number of values to generate
       
   520      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   521      * @param randomNumberBound the bound (exclusive) of each random value
       
   522      * @return a stream of pseudorandom {@code int} values,
       
   523      *         each with the given origin (inclusive) and bound (exclusive)
       
   524      * @throws IllegalArgumentException if {@code streamSize} is
       
   525      *         less than zero, or {@code randomNumberOrigin}
       
   526      *         is greater than or equal to {@code randomNumberBound}
       
   527      * @since 1.8
       
   528      */
       
   529     public IntStream ints(long streamSize, int randomNumberOrigin,
       
   530                           int randomNumberBound) {
       
   531         if (streamSize < 0L)
       
   532             throw new IllegalArgumentException(BAD_SIZE);
       
   533         if (randomNumberOrigin >= randomNumberBound)
       
   534             throw new IllegalArgumentException(BAD_RANGE);
       
   535         return StreamSupport.intStream
       
   536             (new RandomIntsSpliterator
       
   537              (0L, streamSize, randomNumberOrigin, randomNumberBound),
       
   538              false);
       
   539     }
       
   540 
       
   541     /**
       
   542      * Returns an effectively unlimited stream of pseudorandom {@code
       
   543      * int} values, each conforming to the given origin (inclusive) and bound
       
   544      * (exclusive).
       
   545      *
       
   546      * @implNote This method is implemented to be equivalent to {@code
       
   547      * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
       
   548      *
       
   549      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   550      * @param randomNumberBound the bound (exclusive) of each random value
       
   551      * @return a stream of pseudorandom {@code int} values,
       
   552      *         each with the given origin (inclusive) and bound (exclusive)
       
   553      * @throws IllegalArgumentException if {@code randomNumberOrigin}
       
   554      *         is greater than or equal to {@code randomNumberBound}
       
   555      * @since 1.8
       
   556      */
       
   557     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
       
   558         if (randomNumberOrigin >= randomNumberBound)
       
   559             throw new IllegalArgumentException(BAD_RANGE);
       
   560         return StreamSupport.intStream
       
   561             (new RandomIntsSpliterator
       
   562              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
       
   563              false);
       
   564     }
       
   565 
       
   566     /**
       
   567      * Returns a stream producing the given {@code streamSize} number of
       
   568      * pseudorandom {@code long} values.
       
   569      *
       
   570      * @param streamSize the number of values to generate
       
   571      * @return a stream of pseudorandom {@code long} values
       
   572      * @throws IllegalArgumentException if {@code streamSize} is
       
   573      *         less than zero
       
   574      * @since 1.8
       
   575      */
       
   576     public LongStream longs(long streamSize) {
       
   577         if (streamSize < 0L)
       
   578             throw new IllegalArgumentException(BAD_SIZE);
       
   579         return StreamSupport.longStream
       
   580             (new RandomLongsSpliterator
       
   581              (0L, streamSize, Long.MAX_VALUE, 0L),
       
   582              false);
       
   583     }
       
   584 
       
   585     /**
       
   586      * Returns an effectively unlimited stream of pseudorandom {@code long}
       
   587      * values.
       
   588      *
       
   589      * @implNote This method is implemented to be equivalent to {@code
       
   590      * longs(Long.MAX_VALUE)}.
       
   591      *
       
   592      * @return a stream of pseudorandom {@code long} values
       
   593      * @since 1.8
       
   594      */
       
   595     public LongStream longs() {
       
   596         return StreamSupport.longStream
       
   597             (new RandomLongsSpliterator
       
   598              (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
       
   599              false);
       
   600     }
       
   601 
       
   602     /**
       
   603      * Returns a stream producing the given {@code streamSize} number of
       
   604      * pseudorandom {@code long}, each conforming to the given origin
       
   605      * (inclusive) and bound (exclusive).
       
   606      *
       
   607      * @param streamSize the number of values to generate
       
   608      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   609      * @param randomNumberBound the bound (exclusive) of each random value
       
   610      * @return a stream of pseudorandom {@code long} values,
       
   611      *         each with the given origin (inclusive) and bound (exclusive)
       
   612      * @throws IllegalArgumentException if {@code streamSize} is
       
   613      *         less than zero, or {@code randomNumberOrigin}
       
   614      *         is greater than or equal to {@code randomNumberBound}
       
   615      * @since 1.8
       
   616      */
       
   617     public LongStream longs(long streamSize, long randomNumberOrigin,
       
   618                             long randomNumberBound) {
       
   619         if (streamSize < 0L)
       
   620             throw new IllegalArgumentException(BAD_SIZE);
       
   621         if (randomNumberOrigin >= randomNumberBound)
       
   622             throw new IllegalArgumentException(BAD_RANGE);
       
   623         return StreamSupport.longStream
       
   624             (new RandomLongsSpliterator
       
   625              (0L, streamSize, randomNumberOrigin, randomNumberBound),
       
   626              false);
       
   627     }
       
   628 
       
   629     /**
       
   630      * Returns an effectively unlimited stream of pseudorandom {@code
       
   631      * long} values, each conforming to the given origin (inclusive) and bound
       
   632      * (exclusive).
       
   633      *
       
   634      * @implNote This method is implemented to be equivalent to {@code
       
   635      * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
       
   636      *
       
   637      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   638      * @param randomNumberBound the bound (exclusive) of each random value
       
   639      * @return a stream of pseudorandom {@code long} values,
       
   640      *         each with the given origin (inclusive) and bound (exclusive)
       
   641      * @throws IllegalArgumentException if {@code randomNumberOrigin}
       
   642      *         is greater than or equal to {@code randomNumberBound}
       
   643      * @since 1.8
       
   644      */
       
   645     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
       
   646         if (randomNumberOrigin >= randomNumberBound)
       
   647             throw new IllegalArgumentException(BAD_RANGE);
       
   648         return StreamSupport.longStream
       
   649             (new RandomLongsSpliterator
       
   650              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
       
   651              false);
       
   652     }
       
   653 
       
   654     /**
       
   655      * Returns a stream producing the given {@code streamSize} number of
       
   656      * pseudorandom {@code double} values, each between zero
       
   657      * (inclusive) and one (exclusive).
       
   658      *
       
   659      * @param streamSize the number of values to generate
       
   660      * @return a stream of {@code double} values
       
   661      * @throws IllegalArgumentException if {@code streamSize} is
       
   662      *         less than zero
       
   663      * @since 1.8
       
   664      */
       
   665     public DoubleStream doubles(long streamSize) {
       
   666         if (streamSize < 0L)
       
   667             throw new IllegalArgumentException(BAD_SIZE);
       
   668         return StreamSupport.doubleStream
       
   669             (new RandomDoublesSpliterator
       
   670              (0L, streamSize, Double.MAX_VALUE, 0.0),
       
   671              false);
       
   672     }
       
   673 
       
   674     /**
       
   675      * Returns an effectively unlimited stream of pseudorandom {@code
       
   676      * double} values, each between zero (inclusive) and one
       
   677      * (exclusive).
       
   678      *
       
   679      * @implNote This method is implemented to be equivalent to {@code
       
   680      * doubles(Long.MAX_VALUE)}.
       
   681      *
       
   682      * @return a stream of pseudorandom {@code double} values
       
   683      * @since 1.8
       
   684      */
       
   685     public DoubleStream doubles() {
       
   686         return StreamSupport.doubleStream
       
   687             (new RandomDoublesSpliterator
       
   688              (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
       
   689              false);
       
   690     }
       
   691 
       
   692     /**
       
   693      * Returns a stream producing the given {@code streamSize} number of
       
   694      * pseudorandom {@code double} values, each conforming to the given origin
       
   695      * (inclusive) and bound (exclusive).
       
   696      *
       
   697      * @param streamSize the number of values to generate
       
   698      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   699      * @param randomNumberBound the bound (exclusive) of each random value
       
   700      * @return a stream of pseudorandom {@code double} values,
       
   701      *         each with the given origin (inclusive) and bound (exclusive)
       
   702      * @throws IllegalArgumentException if {@code streamSize} is
       
   703      *         less than zero, or {@code randomNumberOrigin}
       
   704      *         is greater than or equal to {@code randomNumberBound}
       
   705      * @since 1.8
       
   706      */
       
   707     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
       
   708                                 double randomNumberBound) {
       
   709         if (streamSize < 0L)
       
   710             throw new IllegalArgumentException(BAD_SIZE);
       
   711         if (!(randomNumberOrigin < randomNumberBound))
       
   712             throw new IllegalArgumentException(BAD_RANGE);
       
   713         return StreamSupport.doubleStream
       
   714             (new RandomDoublesSpliterator
       
   715              (0L, streamSize, randomNumberOrigin, randomNumberBound),
       
   716              false);
       
   717     }
       
   718 
       
   719     /**
       
   720      * Returns an effectively unlimited stream of pseudorandom {@code
       
   721      * double} values, each conforming to the given origin (inclusive) and bound
       
   722      * (exclusive).
       
   723      *
       
   724      * @implNote This method is implemented to be equivalent to {@code
       
   725      * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
       
   726      *
       
   727      * @param randomNumberOrigin the origin (inclusive) of each random value
       
   728      * @param randomNumberBound the bound (exclusive) of each random value
       
   729      * @return a stream of pseudorandom {@code double} values,
       
   730      *         each with the given origin (inclusive) and bound (exclusive)
       
   731      * @throws IllegalArgumentException if {@code randomNumberOrigin}
       
   732      *         is greater than or equal to {@code randomNumberBound}
       
   733      * @since 1.8
       
   734      */
       
   735     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
       
   736         if (!(randomNumberOrigin < randomNumberBound))
       
   737             throw new IllegalArgumentException(BAD_RANGE);
       
   738         return StreamSupport.doubleStream
       
   739             (new RandomDoublesSpliterator
       
   740              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
       
   741              false);
       
   742     }
       
   743 
       
   744     /**
       
   745      * Spliterator for int streams.  We multiplex the four int
       
   746      * versions into one class by treating a bound less than origin as
       
   747      * unbounded, and also by treating "infinite" as equivalent to
       
   748      * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
       
   749      * approach. The long and double versions of this class are
       
   750      * identical except for types.
       
   751      */
       
   752     private static final class RandomIntsSpliterator
       
   753             implements Spliterator.OfInt {
       
   754         long index;
       
   755         final long fence;
       
   756         final int origin;
       
   757         final int bound;
       
   758         RandomIntsSpliterator(long index, long fence,
       
   759                               int origin, int bound) {
       
   760             this.index = index; this.fence = fence;
       
   761             this.origin = origin; this.bound = bound;
       
   762         }
       
   763 
       
   764         public RandomIntsSpliterator trySplit() {
       
   765             long i = index, m = (i + fence) >>> 1;
       
   766             return (m <= i) ? null :
       
   767                 new RandomIntsSpliterator(i, index = m, origin, bound);
       
   768         }
       
   769 
       
   770         public long estimateSize() {
       
   771             return fence - index;
       
   772         }
       
   773 
       
   774         public int characteristics() {
       
   775             return (Spliterator.SIZED | Spliterator.SUBSIZED |
       
   776                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
       
   777         }
       
   778 
       
   779         public boolean tryAdvance(IntConsumer consumer) {
       
   780             if (consumer == null) throw new NullPointerException();
       
   781             long i = index, f = fence;
       
   782             if (i < f) {
       
   783                 consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
       
   784                 index = i + 1;
       
   785                 return true;
       
   786             }
       
   787             return false;
       
   788         }
       
   789 
       
   790         public void forEachRemaining(IntConsumer consumer) {
       
   791             if (consumer == null) throw new NullPointerException();
       
   792             long i = index, f = fence;
       
   793             if (i < f) {
       
   794                 index = f;
       
   795                 int o = origin, b = bound;
       
   796                 ThreadLocalRandom rng = ThreadLocalRandom.current();
       
   797                 do {
       
   798                     consumer.accept(rng.internalNextInt(o, b));
       
   799                 } while (++i < f);
       
   800             }
       
   801         }
       
   802     }
       
   803 
       
   804     /**
       
   805      * Spliterator for long streams.
       
   806      */
       
   807     private static final class RandomLongsSpliterator
       
   808             implements Spliterator.OfLong {
       
   809         long index;
       
   810         final long fence;
       
   811         final long origin;
       
   812         final long bound;
       
   813         RandomLongsSpliterator(long index, long fence,
       
   814                                long origin, long bound) {
       
   815             this.index = index; this.fence = fence;
       
   816             this.origin = origin; this.bound = bound;
       
   817         }
       
   818 
       
   819         public RandomLongsSpliterator trySplit() {
       
   820             long i = index, m = (i + fence) >>> 1;
       
   821             return (m <= i) ? null :
       
   822                 new RandomLongsSpliterator(i, index = m, origin, bound);
       
   823         }
       
   824 
       
   825         public long estimateSize() {
       
   826             return fence - index;
       
   827         }
       
   828 
       
   829         public int characteristics() {
       
   830             return (Spliterator.SIZED | Spliterator.SUBSIZED |
       
   831                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
       
   832         }
       
   833 
       
   834         public boolean tryAdvance(LongConsumer consumer) {
       
   835             if (consumer == null) throw new NullPointerException();
       
   836             long i = index, f = fence;
       
   837             if (i < f) {
       
   838                 consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
       
   839                 index = i + 1;
       
   840                 return true;
       
   841             }
       
   842             return false;
       
   843         }
       
   844 
       
   845         public void forEachRemaining(LongConsumer consumer) {
       
   846             if (consumer == null) throw new NullPointerException();
       
   847             long i = index, f = fence;
       
   848             if (i < f) {
       
   849                 index = f;
       
   850                 long o = origin, b = bound;
       
   851                 ThreadLocalRandom rng = ThreadLocalRandom.current();
       
   852                 do {
       
   853                     consumer.accept(rng.internalNextLong(o, b));
       
   854                 } while (++i < f);
       
   855             }
       
   856         }
       
   857 
       
   858     }
       
   859 
       
   860     /**
       
   861      * Spliterator for double streams.
       
   862      */
       
   863     private static final class RandomDoublesSpliterator
       
   864             implements Spliterator.OfDouble {
       
   865         long index;
       
   866         final long fence;
       
   867         final double origin;
       
   868         final double bound;
       
   869         RandomDoublesSpliterator(long index, long fence,
       
   870                                  double origin, double bound) {
       
   871             this.index = index; this.fence = fence;
       
   872             this.origin = origin; this.bound = bound;
       
   873         }
       
   874 
       
   875         public RandomDoublesSpliterator trySplit() {
       
   876             long i = index, m = (i + fence) >>> 1;
       
   877             return (m <= i) ? null :
       
   878                 new RandomDoublesSpliterator(i, index = m, origin, bound);
       
   879         }
       
   880 
       
   881         public long estimateSize() {
       
   882             return fence - index;
       
   883         }
       
   884 
       
   885         public int characteristics() {
       
   886             return (Spliterator.SIZED | Spliterator.SUBSIZED |
       
   887                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
       
   888         }
       
   889 
       
   890         public boolean tryAdvance(DoubleConsumer consumer) {
       
   891             if (consumer == null) throw new NullPointerException();
       
   892             long i = index, f = fence;
       
   893             if (i < f) {
       
   894                 consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
       
   895                 index = i + 1;
       
   896                 return true;
       
   897             }
       
   898             return false;
       
   899         }
       
   900 
       
   901         public void forEachRemaining(DoubleConsumer consumer) {
       
   902             if (consumer == null) throw new NullPointerException();
       
   903             long i = index, f = fence;
       
   904             if (i < f) {
       
   905                 index = f;
       
   906                 double o = origin, b = bound;
       
   907                 ThreadLocalRandom rng = ThreadLocalRandom.current();
       
   908                 do {
       
   909                     consumer.accept(rng.internalNextDouble(o, b));
       
   910                 } while (++i < f);
       
   911             }
       
   912         }
       
   913     }
       
   914 
       
   915 
   221 
   916     // Within-package utilities
   222     // Within-package utilities
   917 
   223 
   918     /*
   224     /*
   919      * Descriptions of the usages of the methods below can be found in
   225      * Descriptions of the usages of the methods below can be found in
  1036 
   342 
  1037     /**
   343     /**
  1038      * The increment of seeder per new instance.
   344      * The increment of seeder per new instance.
  1039      */
   345      */
  1040     private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
   346     private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
  1041 
       
  1042     /**
       
  1043      * The least non-zero value returned by nextDouble(). This value
       
  1044      * is scaled by a random value of 53 bits to produce a result.
       
  1045      */
       
  1046     private static final double DOUBLE_UNIT = 0x1.0p-53;  // 1.0  / (1L << 53)
       
  1047     private static final float  FLOAT_UNIT  = 0x1.0p-24f; // 1.0f / (1 << 24)
       
  1048 
   347 
  1049     // IllegalArgumentException messages
   348     // IllegalArgumentException messages
  1050     static final String BAD_BOUND = "bound must be positive";
   349     static final String BAD_BOUND = "bound must be positive";
  1051     static final String BAD_RANGE = "bound must be greater than origin";
   350     static final String BAD_RANGE = "bound must be greater than origin";
  1052     static final String BAD_SIZE  = "size must be non-negative";
   351     static final String BAD_SIZE  = "size must be non-negative";
  1064     private static final long INHERITABLETHREADLOCALS
   363     private static final long INHERITABLETHREADLOCALS
  1065         = U.objectFieldOffset(Thread.class, "inheritableThreadLocals");
   364         = U.objectFieldOffset(Thread.class, "inheritableThreadLocals");
  1066     private static final long INHERITEDACCESSCONTROLCONTEXT
   365     private static final long INHERITEDACCESSCONTROLCONTEXT
  1067         = U.objectFieldOffset(Thread.class, "inheritedAccessControlContext");
   366         = U.objectFieldOffset(Thread.class, "inheritedAccessControlContext");
  1068 
   367 
  1069     /** Rarely-used holder for the second of a pair of Gaussians */
       
  1070     private static final ThreadLocal<Double> nextLocalGaussian =
       
  1071         new ThreadLocal<>();
       
  1072 
       
  1073     /** Generates per-thread initialization/probe field */
   368     /** Generates per-thread initialization/probe field */
  1074     private static final AtomicInteger probeGenerator = new AtomicInteger();
   369     private static final AtomicInteger probeGenerator = new AtomicInteger();
  1075 
   370 
  1076     /** The common ThreadLocalRandom */
   371     /** The common ThreadLocalRandom */
  1077     static final ThreadLocalRandom instance = new ThreadLocalRandom();
   372     static final ThreadLocalRandom instance = new ThreadLocalRandom();
  1078 
   373 
  1079     /**
   374     /**
  1080      * The next seed for default constructors.
   375      * The next seed for default constructors.
  1081      */
   376      */
  1082     private static final AtomicLong seeder
   377     private static final AtomicLong seeder
  1083         = new AtomicLong(mix64(System.currentTimeMillis()) ^
   378         = new AtomicLong(RandomSupport.mixMurmur64(System.currentTimeMillis()) ^
  1084                          mix64(System.nanoTime()));
   379                          RandomSupport.mixMurmur64(System.nanoTime()));
  1085 
   380 
  1086     // at end of <clinit> to survive static initialization circularity
   381     // at end of <clinit> to survive static initialization circularity
  1087     static {
   382     static {
  1088         String sec = VM.getSavedProperty("java.util.secureRandomSeed");
   383         String sec = VM.getSavedProperty("java.util.secureRandomSeed");
  1089         if (Boolean.parseBoolean(sec)) {
   384         if (Boolean.parseBoolean(sec)) {