1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  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
  33  * http://creativecommons.org/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent;
  37 
  38 import java.io.ObjectStreamField;
  39 import sun.security.provider.SeedGenerator;
  40 import java.util.Random;
  41 import java.util.Spliterator;
  42 import java.util.concurrent.atomic.AtomicInteger;
  43 import java.util.concurrent.atomic.AtomicLong;
  44 import java.util.function.DoubleConsumer;
  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 
  52 /**
  53  * A random number generator isolated to the current thread.  Like the
  54  * global {@link java.util.Random} generator used by the {@link
  55  * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
  56  * with an internally generated seed that may not otherwise be
  57  * modified. When applicable, use of {@code ThreadLocalRandom} rather
  58  * than shared {@code Random} objects in concurrent programs will
  59  * typically encounter much less overhead and contention.  Use of
  60  * {@code ThreadLocalRandom} is particularly appropriate when multiple
  61  * tasks (for example, each a {@link ForkJoinTask}) use random numbers
  62  * in parallel in thread pools.
  63  *
  64  * <p>Usages of this class should typically be of the form:
  65  * {@code ThreadLocalRandom.current().nextX(...)} (where
  66  * {@code X} is {@code Int}, {@code Long}, etc).
  67  * When all usages are of this form, it is never possible to
  68  * accidently share a {@code ThreadLocalRandom} across multiple threads.
  69  *
  70  * <p>This class also provides additional commonly used bounded random
  71  * generation methods.
  72  *
  73  * <p>Instances of {@code ThreadLocalRandom} are not cryptographically
  74  * secure.  Consider instead using {@link java.security.SecureRandom}
  75  * in security-sensitive applications. Additionally,
  76  * default-constructed instances do not use a cryptographically random
  77  * seed unless the {@linkplain System#getProperty system property}
  78  * {@code java.util.secureRandomSeed} is set to {@code true}.
  79  *
  80  * @since 1.7
  81  * @author Doug Lea
  82  */
  83 public class ThreadLocalRandom extends Random {
  84     /*
  85      * This class implements the java.util.Random API (and subclasses
  86      * Random) using a single static instance that accesses random
  87      * number state held in class Thread (primarily, field
  88      * threadLocalRandomSeed). In doing so, it also provides a home
  89      * for managing package-private utilities that rely on exactly the
  90      * same state as needed to maintain the ThreadLocalRandom
  91      * instances. We leverage the need for an initialization flag
  92      * field to also use it as a "probe" -- a self-adjusting thread
  93      * hash used for contention avoidance, as well as a secondary
  94      * simpler (xorShift) random seed that is conservatively used to
  95      * avoid otherwise surprising users by hijacking the
  96      * ThreadLocalRandom sequence.  The dual use is a marriage of
  97      * convenience, but is a simple and efficient way of reducing
  98      * application-level overhead and footprint of most concurrent
  99      * programs.
 100      *
 101      * Even though this class subclasses java.util.Random, it uses the
 102      * same basic algorithm as java.util.SplittableRandom.  (See its
 103      * internal documentation for explanations, which are not repeated
 104      * here.)  Because ThreadLocalRandoms are not splittable
 105      * though, we use only a single 64bit gamma.
 106      *
 107      * Because this class is in a different package than class Thread,
 108      * field access methods use Unsafe to bypass access control rules.
 109      * To conform to the requirements of the Random superclass
 110      * constructor, the common static ThreadLocalRandom maintains an
 111      * "initialized" field for the sake of rejecting user calls to
 112      * setSeed while still allowing a call from constructor.  Note
 113      * that serialization is completely unnecessary because there is
 114      * only a static singleton.  But we generate a serial form
 115      * containing "rnd" and "initialized" fields to ensure
 116      * compatibility across versions.
 117      *
 118      * Implementations of non-core methods are mostly the same as in
 119      * SplittableRandom, that were in part derived from a previous
 120      * version of this class.
 121      *
 122      * The nextLocalGaussian ThreadLocal supports the very rarely used
 123      * nextGaussian method by providing a holder for the second of a
 124      * pair of them. As is true for the base class version of this
 125      * method, this time/space tradeoff is probably never worthwhile,
 126      * but we provide identical statistical properties.
 127      */
 128 
 129     /** Generates per-thread initialization/probe field */
 130     private static final AtomicInteger probeGenerator =
 131         new AtomicInteger();
 132 
 133     /**
 134      * The next seed for default constructors.
 135      */
 136     private static final AtomicLong seeder = new AtomicLong(initialSeed());
 137 
 138     private static long initialSeed() {
 139         try (SeedGenerator sg = SeedGenerator.getNativeInstance()) {
 140             byte[] seedBytes = new byte[8];
 141             sg.getSeedBytes(seedBytes);
 142             long s = (long)(seedBytes[0]) & 0xffL;
 143             for (int i = 1; i < 8; ++i)
 144                 s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
 145             return s ^ mix64(System.currentTimeMillis()) ^
 146                    mix64(System.nanoTime());
 147         }
 148     }
 149 
 150     /**
 151      * The seed increment
 152      */
 153     private static final long GAMMA = 0x9e3779b97f4a7c15L;
 154 
 155     /**
 156      * The increment for generating probe values
 157      */
 158     private static final int PROBE_INCREMENT = 0x9e3779b9;
 159 
 160     /**
 161      * The increment of seeder per new instance
 162      */
 163     private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
 164 
 165     // Constants from SplittableRandom
 166     private static final double DOUBLE_UNIT = 0x1.0p-53;  // 1.0  / (1L << 53)
 167     private static final float  FLOAT_UNIT  = 0x1.0p-24f; // 1.0f / (1 << 24)
 168 
 169     /** Rarely-used holder for the second of a pair of Gaussians */
 170     private static final ThreadLocal<Double> nextLocalGaussian =
 171         new ThreadLocal<Double>();
 172 
 173     private static long mix64(long z) {
 174         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
 175         z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
 176         return z ^ (z >>> 33);
 177     }
 178 
 179     private static int mix32(long z) {
 180         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
 181         return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
 182     }
 183 
 184     /**
 185      * Field used only during singleton initialization.
 186      * True when constructor completes.
 187      */
 188     boolean initialized;
 189 
 190     /** Constructor used only for static singleton */
 191     private ThreadLocalRandom() {
 192         initialized = true; // false during super() call
 193     }
 194 
 195     /** The common ThreadLocalRandom */
 196     static final ThreadLocalRandom instance = new ThreadLocalRandom();
 197 
 198     /**
 199      * Initialize Thread fields for the current thread.  Called only
 200      * when Thread.threadLocalRandomProbe is zero, indicating that a
 201      * thread local seed value needs to be generated. Note that even
 202      * though the initialization is purely thread-local, we need to
 203      * rely on (static) atomic generators to initialize the values.
 204      */
 205     static final void localInit() {
 206         int p = probeGenerator.addAndGet(PROBE_INCREMENT);
 207         int probe = (p == 0) ? 1 : p; // skip 0
 208         long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
 209         Thread t = Thread.currentThread();
 210         UNSAFE.putLong(t, SEED, seed);
 211         UNSAFE.putInt(t, PROBE, probe);
 212     }
 213 
 214     /**
 215      * Returns the current thread's {@code ThreadLocalRandom}.
 216      *
 217      * @return the current thread's {@code ThreadLocalRandom}
 218      */
 219     public static ThreadLocalRandom current() {
 220         if (UNSAFE.getInt(Thread.currentThread(), PROBE) == 0)
 221             localInit();
 222         return instance;
 223     }
 224 
 225     /**
 226      * Throws {@code UnsupportedOperationException}.  Setting seeds in
 227      * this generator is not supported.
 228      *
 229      * @throws UnsupportedOperationException always
 230      */
 231     public void setSeed(long seed) {
 232         // only allow call from super() constructor
 233         if (initialized)
 234             throw new UnsupportedOperationException();
 235     }
 236 
 237     final long nextSeed() {
 238         Thread t; long r; // read and update per-thread seed
 239         UNSAFE.putLong(t = Thread.currentThread(), SEED,
 240                        r = UNSAFE.getLong(t, SEED) + GAMMA);
 241         return r;
 242     }
 243 
 244     // We must define this, but never use it.
 245     protected int next(int bits) {
 246         return (int)(mix64(nextSeed()) >>> (64 - bits));
 247     }
 248 
 249     // IllegalArgumentException messages
 250     static final String BadBound = "bound must be positive";
 251     static final String BadRange = "bound must be greater than origin";
 252     static final String BadSize  = "size must be non-negative";
 253 
 254     /**
 255      * The form of nextLong used by LongStream Spliterators.  If
 256      * origin is greater than bound, acts as unbounded form of
 257      * nextLong, else as bounded form.
 258      *
 259      * @param origin the least value, unless greater than bound
 260      * @param bound the upper bound (exclusive), must not equal origin
 261      * @return a pseudorandom value
 262      */
 263     final long internalNextLong(long origin, long bound) {
 264         long r = mix64(nextSeed());
 265         if (origin < bound) {
 266             long n = bound - origin, m = n - 1;
 267             if ((n & m) == 0L)  // power of two
 268                 r = (r & m) + origin;
 269             else if (n > 0L) {  // reject over-represented candidates
 270                 for (long u = r >>> 1;            // ensure nonnegative
 271                      u + m - (r = u % n) < 0L;    // rejection check
 272                      u = mix64(nextSeed()) >>> 1) // retry
 273                     ;
 274                 r += origin;
 275             }
 276             else {              // range not representable as long
 277                 while (r < origin || r >= bound)
 278                     r = mix64(nextSeed());
 279             }
 280         }
 281         return r;
 282     }
 283 
 284     /**
 285      * The form of nextInt used by IntStream Spliterators.
 286      * Exactly the same as long version, except for types.
 287      *
 288      * @param origin the least value, unless greater than bound
 289      * @param bound the upper bound (exclusive), must not equal origin
 290      * @return a pseudorandom value
 291      */
 292     final int internalNextInt(int origin, int bound) {
 293         int r = mix32(nextSeed());
 294         if (origin < bound) {
 295             int n = bound - origin, m = n - 1;
 296             if ((n & m) == 0)
 297                 r = (r & m) + origin;
 298             else if (n > 0) {
 299                 for (int u = r >>> 1;
 300                      u + m - (r = u % n) < 0;
 301                      u = mix32(nextSeed()) >>> 1)
 302                     ;
 303                 r += origin;
 304             }
 305             else {
 306                 while (r < origin || r >= bound)
 307                     r = mix32(nextSeed());
 308             }
 309         }
 310         return r;
 311     }
 312 
 313     /**
 314      * The form of nextDouble used by DoubleStream Spliterators.
 315      *
 316      * @param origin the least value, unless greater than bound
 317      * @param bound the upper bound (exclusive), must not equal origin
 318      * @return a pseudorandom value
 319      */
 320     final double internalNextDouble(double origin, double bound) {
 321         double r = (nextLong() >>> 11) * DOUBLE_UNIT;
 322         if (origin < bound) {
 323             r = r * (bound - origin) + origin;
 324             if (r >= bound) // correct for rounding
 325                 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
 326         }
 327         return r;
 328     }
 329 
 330     /**
 331      * Returns a pseudorandom {@code int} value.
 332      *
 333      * @return a pseudorandom {@code int} value
 334      */
 335     public int nextInt() {
 336         return mix32(nextSeed());
 337     }
 338 
 339     /**
 340      * Returns a pseudorandom {@code int} value between zero (inclusive)
 341      * and the specified bound (exclusive).
 342      *
 343      * @param bound the upper bound (exclusive).  Must be positive.
 344      * @return a pseudorandom {@code int} value between zero
 345      *         (inclusive) and the bound (exclusive)
 346      * @throws IllegalArgumentException if {@code bound} is not positive
 347      */
 348     public int nextInt(int bound) {
 349         if (bound <= 0)
 350             throw new IllegalArgumentException(BadBound);
 351         int r = mix32(nextSeed());
 352         int m = bound - 1;
 353         if ((bound & m) == 0) // power of two
 354             r &= m;
 355         else { // reject over-represented candidates
 356             for (int u = r >>> 1;
 357                  u + m - (r = u % bound) < 0;
 358                  u = mix32(nextSeed()) >>> 1)
 359                 ;
 360         }
 361         return r;
 362     }
 363 
 364     /**
 365      * Returns a pseudorandom {@code int} value between the specified
 366      * origin (inclusive) and the specified bound (exclusive).
 367      *
 368      * @param origin the least value returned
 369      * @param bound the upper bound (exclusive)
 370      * @return a pseudorandom {@code int} value between the origin
 371      *         (inclusive) and the bound (exclusive)
 372      * @throws IllegalArgumentException if {@code origin} is greater than
 373      *         or equal to {@code bound}
 374      */
 375     public int nextInt(int origin, int bound) {
 376         if (origin >= bound)
 377             throw new IllegalArgumentException(BadRange);
 378         return internalNextInt(origin, bound);
 379     }
 380 
 381     /**
 382      * Returns a pseudorandom {@code long} value.
 383      *
 384      * @return a pseudorandom {@code long} value
 385      */
 386     public long nextLong() {
 387         return mix64(nextSeed());
 388     }
 389 
 390     /**
 391      * Returns a pseudorandom {@code long} value between zero (inclusive)
 392      * and the specified bound (exclusive).
 393      *
 394      * @param bound the upper bound (exclusive).  Must be positive.
 395      * @return a pseudorandom {@code long} value between zero
 396      *         (inclusive) and the bound (exclusive)
 397      * @throws IllegalArgumentException if {@code bound} is not positive
 398      */
 399     public long nextLong(long bound) {
 400         if (bound <= 0)
 401             throw new IllegalArgumentException(BadBound);
 402         long r = mix64(nextSeed());
 403         long m = bound - 1;
 404         if ((bound & m) == 0L) // power of two
 405             r &= m;
 406         else { // reject over-represented candidates
 407             for (long u = r >>> 1;
 408                  u + m - (r = u % bound) < 0L;
 409                  u = mix64(nextSeed()) >>> 1)
 410                 ;
 411         }
 412         return r;
 413     }
 414 
 415     /**
 416      * Returns a pseudorandom {@code long} value between the specified
 417      * origin (inclusive) and the specified bound (exclusive).
 418      *
 419      * @param origin the least value returned
 420      * @param bound the upper bound (exclusive)
 421      * @return a pseudorandom {@code long} value between the origin
 422      *         (inclusive) and the bound (exclusive)
 423      * @throws IllegalArgumentException if {@code origin} is greater than
 424      *         or equal to {@code bound}
 425      */
 426     public long nextLong(long origin, long bound) {
 427         if (origin >= bound)
 428             throw new IllegalArgumentException(BadRange);
 429         return internalNextLong(origin, bound);
 430     }
 431 
 432     /**
 433      * Returns a pseudorandom {@code double} value between zero
 434      * (inclusive) and one (exclusive).
 435      *
 436      * @return a pseudorandom {@code double} value between zero
 437      *         (inclusive) and one (exclusive)
 438      */
 439     public double nextDouble() {
 440         return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
 441     }
 442 
 443     /**
 444      * Returns a pseudorandom {@code double} value between 0.0
 445      * (inclusive) and the specified bound (exclusive).
 446      *
 447      * @param bound the upper bound (exclusive).  Must be positive.
 448      * @return a pseudorandom {@code double} value between zero
 449      *         (inclusive) and the bound (exclusive)
 450      * @throws IllegalArgumentException if {@code bound} is not positive
 451      */
 452     public double nextDouble(double bound) {
 453         if (!(bound > 0.0))
 454             throw new IllegalArgumentException(BadBound);
 455         double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
 456         return (result < bound) ?  result : // correct for rounding
 457             Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
 458     }
 459 
 460     /**
 461      * Returns a pseudorandom {@code double} value between the specified
 462      * origin (inclusive) and bound (exclusive).
 463      *
 464      * @param origin the least value returned
 465      * @param bound the upper bound (exclusive)
 466      * @return a pseudorandom {@code double} value between the origin
 467      *         (inclusive) and the bound (exclusive)
 468      * @throws IllegalArgumentException if {@code origin} is greater than
 469      *         or equal to {@code bound}
 470      */
 471     public double nextDouble(double origin, double bound) {
 472         if (!(origin < bound))
 473             throw new IllegalArgumentException(BadRange);
 474         return internalNextDouble(origin, bound);
 475     }
 476 
 477     /**
 478      * Returns a pseudorandom {@code boolean} value.
 479      *
 480      * @return a pseudorandom {@code boolean} value
 481      */
 482     public boolean nextBoolean() {
 483         return mix32(nextSeed()) < 0;
 484     }
 485 
 486     /**
 487      * Returns a pseudorandom {@code float} value between zero
 488      * (inclusive) and one (exclusive).
 489      *
 490      * @return a pseudorandom {@code float} value between zero
 491      *         (inclusive) and one (exclusive)
 492      */
 493     public float nextFloat() {
 494         return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
 495     }
 496 
 497     public double nextGaussian() {
 498         // Use nextLocalGaussian instead of nextGaussian field
 499         Double d = nextLocalGaussian.get();
 500         if (d != null) {
 501             nextLocalGaussian.set(null);
 502             return d.doubleValue();
 503         }
 504         double v1, v2, s;
 505         do {
 506             v1 = 2 * nextDouble() - 1; // between -1 and 1
 507             v2 = 2 * nextDouble() - 1; // between -1 and 1
 508             s = v1 * v1 + v2 * v2;
 509         } while (s >= 1 || s == 0);
 510         double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
 511         nextLocalGaussian.set(new Double(v2 * multiplier));
 512         return v1 * multiplier;
 513     }
 514 
 515     // stream methods, coded in a way intended to better isolate for
 516     // maintenance purposes the small differences across forms.
 517 
 518     /**
 519      * Returns a stream producing the given {@code streamSize} number of
 520      * pseudorandom {@code int} values.
 521      *
 522      * @param streamSize the number of values to generate
 523      * @return a stream of pseudorandom {@code int} values
 524      * @throws IllegalArgumentException if {@code streamSize} is
 525      *         less than zero
 526      * @since 1.8
 527      */
 528     public IntStream ints(long streamSize) {
 529         if (streamSize < 0L)
 530             throw new IllegalArgumentException(BadSize);
 531         return StreamSupport.intStream
 532             (new RandomIntsSpliterator
 533              (0L, streamSize, Integer.MAX_VALUE, 0),
 534              false);
 535     }
 536 
 537     /**
 538      * Returns an effectively unlimited stream of pseudorandom {@code int}
 539      * values.
 540      *
 541      * @implNote This method is implemented to be equivalent to {@code
 542      * ints(Long.MAX_VALUE)}.
 543      *
 544      * @return a stream of pseudorandom {@code int} values
 545      * @since 1.8
 546      */
 547     public IntStream ints() {
 548         return StreamSupport.intStream
 549             (new RandomIntsSpliterator
 550              (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
 551              false);
 552     }
 553 
 554     /**
 555      * Returns a stream producing the given {@code streamSize} number
 556      * of pseudorandom {@code int} values, each conforming to the given
 557      * origin (inclusive) and bound (exclusive).
 558      *
 559      * @param streamSize the number of values to generate
 560      * @param randomNumberOrigin the origin (inclusive) of each random value
 561      * @param randomNumberBound the bound (exclusive) of each random value
 562      * @return a stream of pseudorandom {@code int} values,
 563      *         each with the given origin (inclusive) and bound (exclusive)
 564      * @throws IllegalArgumentException if {@code streamSize} is
 565      *         less than zero, or {@code randomNumberOrigin}
 566      *         is greater than or equal to {@code randomNumberBound}
 567      * @since 1.8
 568      */
 569     public IntStream ints(long streamSize, int randomNumberOrigin,
 570                           int randomNumberBound) {
 571         if (streamSize < 0L)
 572             throw new IllegalArgumentException(BadSize);
 573         if (randomNumberOrigin >= randomNumberBound)
 574             throw new IllegalArgumentException(BadRange);
 575         return StreamSupport.intStream
 576             (new RandomIntsSpliterator
 577              (0L, streamSize, randomNumberOrigin, randomNumberBound),
 578              false);
 579     }
 580 
 581     /**
 582      * Returns an effectively unlimited stream of pseudorandom {@code
 583      * int} values, each conforming to the given origin (inclusive) and bound
 584      * (exclusive).
 585      *
 586      * @implNote This method is implemented to be equivalent to {@code
 587      * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
 588      *
 589      * @param randomNumberOrigin the origin (inclusive) of each random value
 590      * @param randomNumberBound the bound (exclusive) of each random value
 591      * @return a stream of pseudorandom {@code int} values,
 592      *         each with the given origin (inclusive) and bound (exclusive)
 593      * @throws IllegalArgumentException if {@code randomNumberOrigin}
 594      *         is greater than or equal to {@code randomNumberBound}
 595      * @since 1.8
 596      */
 597     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
 598         if (randomNumberOrigin >= randomNumberBound)
 599             throw new IllegalArgumentException(BadRange);
 600         return StreamSupport.intStream
 601             (new RandomIntsSpliterator
 602              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
 603              false);
 604     }
 605 
 606     /**
 607      * Returns a stream producing the given {@code streamSize} number of
 608      * pseudorandom {@code long} values.
 609      *
 610      * @param streamSize the number of values to generate
 611      * @return a stream of pseudorandom {@code long} values
 612      * @throws IllegalArgumentException if {@code streamSize} is
 613      *         less than zero
 614      * @since 1.8
 615      */
 616     public LongStream longs(long streamSize) {
 617         if (streamSize < 0L)
 618             throw new IllegalArgumentException(BadSize);
 619         return StreamSupport.longStream
 620             (new RandomLongsSpliterator
 621              (0L, streamSize, Long.MAX_VALUE, 0L),
 622              false);
 623     }
 624 
 625     /**
 626      * Returns an effectively unlimited stream of pseudorandom {@code long}
 627      * values.
 628      *
 629      * @implNote This method is implemented to be equivalent to {@code
 630      * longs(Long.MAX_VALUE)}.
 631      *
 632      * @return a stream of pseudorandom {@code long} values
 633      * @since 1.8
 634      */
 635     public LongStream longs() {
 636         return StreamSupport.longStream
 637             (new RandomLongsSpliterator
 638              (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
 639              false);
 640     }
 641 
 642     /**
 643      * Returns a stream producing the given {@code streamSize} number of
 644      * pseudorandom {@code long}, each conforming to the given origin
 645      * (inclusive) and bound (exclusive).
 646      *
 647      * @param streamSize the number of values to generate
 648      * @param randomNumberOrigin the origin (inclusive) of each random value
 649      * @param randomNumberBound the bound (exclusive) of each random value
 650      * @return a stream of pseudorandom {@code long} values,
 651      *         each with the given origin (inclusive) and bound (exclusive)
 652      * @throws IllegalArgumentException if {@code streamSize} is
 653      *         less than zero, or {@code randomNumberOrigin}
 654      *         is greater than or equal to {@code randomNumberBound}
 655      * @since 1.8
 656      */
 657     public LongStream longs(long streamSize, long randomNumberOrigin,
 658                             long randomNumberBound) {
 659         if (streamSize < 0L)
 660             throw new IllegalArgumentException(BadSize);
 661         if (randomNumberOrigin >= randomNumberBound)
 662             throw new IllegalArgumentException(BadRange);
 663         return StreamSupport.longStream
 664             (new RandomLongsSpliterator
 665              (0L, streamSize, randomNumberOrigin, randomNumberBound),
 666              false);
 667     }
 668 
 669     /**
 670      * Returns an effectively unlimited stream of pseudorandom {@code
 671      * long} values, each conforming to the given origin (inclusive) and bound
 672      * (exclusive).
 673      *
 674      * @implNote This method is implemented to be equivalent to {@code
 675      * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
 676      *
 677      * @param randomNumberOrigin the origin (inclusive) of each random value
 678      * @param randomNumberBound the bound (exclusive) of each random value
 679      * @return a stream of pseudorandom {@code long} values,
 680      *         each with the given origin (inclusive) and bound (exclusive)
 681      * @throws IllegalArgumentException if {@code randomNumberOrigin}
 682      *         is greater than or equal to {@code randomNumberBound}
 683      * @since 1.8
 684      */
 685     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
 686         if (randomNumberOrigin >= randomNumberBound)
 687             throw new IllegalArgumentException(BadRange);
 688         return StreamSupport.longStream
 689             (new RandomLongsSpliterator
 690              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
 691              false);
 692     }
 693 
 694     /**
 695      * Returns a stream producing the given {@code streamSize} number of
 696      * pseudorandom {@code double} values, each between zero
 697      * (inclusive) and one (exclusive).
 698      *
 699      * @param streamSize the number of values to generate
 700      * @return a stream of {@code double} values
 701      * @throws IllegalArgumentException if {@code streamSize} is
 702      *         less than zero
 703      * @since 1.8
 704      */
 705     public DoubleStream doubles(long streamSize) {
 706         if (streamSize < 0L)
 707             throw new IllegalArgumentException(BadSize);
 708         return StreamSupport.doubleStream
 709             (new RandomDoublesSpliterator
 710              (0L, streamSize, Double.MAX_VALUE, 0.0),
 711              false);
 712     }
 713 
 714     /**
 715      * Returns an effectively unlimited stream of pseudorandom {@code
 716      * double} values, each between zero (inclusive) and one
 717      * (exclusive).
 718      *
 719      * @implNote This method is implemented to be equivalent to {@code
 720      * doubles(Long.MAX_VALUE)}.
 721      *
 722      * @return a stream of pseudorandom {@code double} values
 723      * @since 1.8
 724      */
 725     public DoubleStream doubles() {
 726         return StreamSupport.doubleStream
 727             (new RandomDoublesSpliterator
 728              (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
 729              false);
 730     }
 731 
 732     /**
 733      * Returns a stream producing the given {@code streamSize} number of
 734      * pseudorandom {@code double} values, each conforming to the given origin
 735      * (inclusive) and bound (exclusive).
 736      *
 737      * @param streamSize the number of values to generate
 738      * @param randomNumberOrigin the origin (inclusive) of each random value
 739      * @param randomNumberBound the bound (exclusive) of each random value
 740      * @return a stream of pseudorandom {@code double} values,
 741      *         each with the given origin (inclusive) and bound (exclusive)
 742      * @throws IllegalArgumentException if {@code streamSize} is
 743      *         less than zero
 744      * @throws IllegalArgumentException if {@code randomNumberOrigin}
 745      *         is greater than or equal to {@code randomNumberBound}
 746      * @since 1.8
 747      */
 748     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
 749                                 double randomNumberBound) {
 750         if (streamSize < 0L)
 751             throw new IllegalArgumentException(BadSize);
 752         if (!(randomNumberOrigin < randomNumberBound))
 753             throw new IllegalArgumentException(BadRange);
 754         return StreamSupport.doubleStream
 755             (new RandomDoublesSpliterator
 756              (0L, streamSize, randomNumberOrigin, randomNumberBound),
 757              false);
 758     }
 759 
 760     /**
 761      * Returns an effectively unlimited stream of pseudorandom {@code
 762      * double} values, each conforming to the given origin (inclusive) and bound
 763      * (exclusive).
 764      *
 765      * @implNote This method is implemented to be equivalent to {@code
 766      * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
 767      *
 768      * @param randomNumberOrigin the origin (inclusive) of each random value
 769      * @param randomNumberBound the bound (exclusive) of each random value
 770      * @return a stream of pseudorandom {@code double} values,
 771      *         each with the given origin (inclusive) and bound (exclusive)
 772      * @throws IllegalArgumentException if {@code randomNumberOrigin}
 773      *         is greater than or equal to {@code randomNumberBound}
 774      * @since 1.8
 775      */
 776     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
 777         if (!(randomNumberOrigin < randomNumberBound))
 778             throw new IllegalArgumentException(BadRange);
 779         return StreamSupport.doubleStream
 780             (new RandomDoublesSpliterator
 781              (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
 782              false);
 783     }
 784 
 785     /**
 786      * Spliterator for int streams.  We multiplex the four int
 787      * versions into one class by treating a bound less than origin as
 788      * unbounded, and also by treating "infinite" as equivalent to
 789      * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
 790      * approach. The long and double versions of this class are
 791      * identical except for types.
 792      */
 793     static final class RandomIntsSpliterator implements Spliterator.OfInt {
 794         long index;
 795         final long fence;
 796         final int origin;
 797         final int bound;
 798         RandomIntsSpliterator(long index, long fence,
 799                               int origin, int bound) {
 800             this.index = index; this.fence = fence;
 801             this.origin = origin; this.bound = bound;
 802         }
 803 
 804         public RandomIntsSpliterator trySplit() {
 805             long i = index, m = (i + fence) >>> 1;
 806             return (m <= i) ? null :
 807                 new RandomIntsSpliterator(i, index = m, origin, bound);
 808         }
 809 
 810         public long estimateSize() {
 811             return fence - index;
 812         }
 813 
 814         public int characteristics() {
 815             return (Spliterator.SIZED | Spliterator.SUBSIZED |
 816                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
 817         }
 818 
 819         public boolean tryAdvance(IntConsumer consumer) {
 820             if (consumer == null) throw new NullPointerException();
 821             long i = index, f = fence;
 822             if (i < f) {
 823                 consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
 824                 index = i + 1;
 825                 return true;
 826             }
 827             return false;
 828         }
 829 
 830         public void forEachRemaining(IntConsumer consumer) {
 831             if (consumer == null) throw new NullPointerException();
 832             long i = index, f = fence;
 833             if (i < f) {
 834                 index = f;
 835                 int o = origin, b = bound;
 836                 ThreadLocalRandom rng = ThreadLocalRandom.current();
 837                 do {
 838                     consumer.accept(rng.internalNextInt(o, b));
 839                 } while (++i < f);
 840             }
 841         }
 842     }
 843 
 844     /**
 845      * Spliterator for long streams.
 846      */
 847     static final class RandomLongsSpliterator implements Spliterator.OfLong {
 848         long index;
 849         final long fence;
 850         final long origin;
 851         final long bound;
 852         RandomLongsSpliterator(long index, long fence,
 853                                long origin, long bound) {
 854             this.index = index; this.fence = fence;
 855             this.origin = origin; this.bound = bound;
 856         }
 857 
 858         public RandomLongsSpliterator trySplit() {
 859             long i = index, m = (i + fence) >>> 1;
 860             return (m <= i) ? null :
 861                 new RandomLongsSpliterator(i, index = m, origin, bound);
 862         }
 863 
 864         public long estimateSize() {
 865             return fence - index;
 866         }
 867 
 868         public int characteristics() {
 869             return (Spliterator.SIZED | Spliterator.SUBSIZED |
 870                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
 871         }
 872 
 873         public boolean tryAdvance(LongConsumer consumer) {
 874             if (consumer == null) throw new NullPointerException();
 875             long i = index, f = fence;
 876             if (i < f) {
 877                 consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
 878                 index = i + 1;
 879                 return true;
 880             }
 881             return false;
 882         }
 883 
 884         public void forEachRemaining(LongConsumer consumer) {
 885             if (consumer == null) throw new NullPointerException();
 886             long i = index, f = fence;
 887             if (i < f) {
 888                 index = f;
 889                 long o = origin, b = bound;
 890                 ThreadLocalRandom rng = ThreadLocalRandom.current();
 891                 do {
 892                     consumer.accept(rng.internalNextLong(o, b));
 893                 } while (++i < f);
 894             }
 895         }
 896 
 897     }
 898 
 899     /**
 900      * Spliterator for double streams.
 901      */
 902     static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
 903         long index;
 904         final long fence;
 905         final double origin;
 906         final double bound;
 907         RandomDoublesSpliterator(long index, long fence,
 908                                  double origin, double bound) {
 909             this.index = index; this.fence = fence;
 910             this.origin = origin; this.bound = bound;
 911         }
 912 
 913         public RandomDoublesSpliterator trySplit() {
 914             long i = index, m = (i + fence) >>> 1;
 915             return (m <= i) ? null :
 916                 new RandomDoublesSpliterator(i, index = m, origin, bound);
 917         }
 918 
 919         public long estimateSize() {
 920             return fence - index;
 921         }
 922 
 923         public int characteristics() {
 924             return (Spliterator.SIZED | Spliterator.SUBSIZED |
 925                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
 926         }
 927 
 928         public boolean tryAdvance(DoubleConsumer consumer) {
 929             if (consumer == null) throw new NullPointerException();
 930             long i = index, f = fence;
 931             if (i < f) {
 932                 consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
 933                 index = i + 1;
 934                 return true;
 935             }
 936             return false;
 937         }
 938 
 939         public void forEachRemaining(DoubleConsumer consumer) {
 940             if (consumer == null) throw new NullPointerException();
 941             long i = index, f = fence;
 942             if (i < f) {
 943                 index = f;
 944                 double o = origin, b = bound;
 945                 ThreadLocalRandom rng = ThreadLocalRandom.current();
 946                 do {
 947                     consumer.accept(rng.internalNextDouble(o, b));
 948                 } while (++i < f);
 949             }
 950         }
 951     }
 952 
 953 
 954     // Within-package utilities
 955 
 956     /*
 957      * Descriptions of the usages of the methods below can be found in
 958      * the classes that use them. Briefly, a thread's "probe" value is
 959      * a non-zero hash code that (probably) does not collide with
 960      * other existing threads with respect to any power of two
 961      * collision space. When it does collide, it is pseudo-randomly
 962      * adjusted (using a Marsaglia XorShift). The nextSecondarySeed
 963      * method is used in the same contexts as ThreadLocalRandom, but
 964      * only for transient usages such as random adaptive spin/block
 965      * sequences for which a cheap RNG suffices and for which it could
 966      * in principle disrupt user-visible statistical properties of the
 967      * main ThreadLocalRandom if we were to use it.
 968      *
 969      * Note: Because of package-protection issues, versions of some
 970      * these methods also appear in some subpackage classes.
 971      */
 972 
 973     /**
 974      * Returns the probe value for the current thread without forcing
 975      * initialization. Note that invoking ThreadLocalRandom.current()
 976      * can be used to force initialization on zero return.
 977      */
 978     static final int getProbe() {
 979         return UNSAFE.getInt(Thread.currentThread(), PROBE);
 980     }
 981 
 982     /**
 983      * Pseudo-randomly advances and records the given probe value for the
 984      * given thread.
 985      */
 986     static final int advanceProbe(int probe) {
 987         probe ^= probe << 13;   // xorshift
 988         probe ^= probe >>> 17;
 989         probe ^= probe << 5;
 990         UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
 991         return probe;
 992     }
 993 
 994     /**
 995      * Returns the pseudo-randomly initialized or updated secondary seed.
 996      */
 997     static final int nextSecondarySeed() {
 998         int r;
 999         Thread t = Thread.currentThread();
1000         if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) {
1001             r ^= r << 13;   // xorshift
1002             r ^= r >>> 17;
1003             r ^= r << 5;
1004         }
1005         else {
1006             localInit();
1007             if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
1008                 r = 1; // avoid zero
1009         }
1010         UNSAFE.putInt(t, SECONDARY, r);
1011         return r;
1012     }
1013 
1014     // Serialization support
1015 
1016     private static final long serialVersionUID = -5851777807851030925L;
1017 
1018     /**
1019      * @serialField rnd long
1020      *              seed for random computations
1021      * @serialField initialized boolean
1022      *              always true
1023      */
1024     private static final ObjectStreamField[] serialPersistentFields = {
1025             new ObjectStreamField("rnd", long.class),
1026             new ObjectStreamField("initialized", boolean.class),
1027     };
1028 
1029     /**
1030      * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
1031      * @param s the stream
1032      * @throws java.io.IOException if an I/O error occurs
1033      */
1034     private void writeObject(java.io.ObjectOutputStream s)
1035         throws java.io.IOException {
1036 
1037         java.io.ObjectOutputStream.PutField fields = s.putFields();
1038         fields.put("rnd", UNSAFE.getLong(Thread.currentThread(), SEED));
1039         fields.put("initialized", true);
1040         s.writeFields();
1041     }
1042 
1043     /**
1044      * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}.
1045      * @return the {@link #current() current} thread's {@code ThreadLocalRandom}
1046      */
1047     private Object readResolve() {
1048         return current();
1049     }
1050 
1051     // Unsafe mechanics
1052     private static final sun.misc.Unsafe UNSAFE;
1053     private static final long SEED;
1054     private static final long PROBE;
1055     private static final long SECONDARY;
1056     static {
1057         try {
1058             UNSAFE = sun.misc.Unsafe.getUnsafe();
1059             Class<?> tk = Thread.class;
1060             SEED = UNSAFE.objectFieldOffset
1061                 (tk.getDeclaredField("threadLocalRandomSeed"));
1062             PROBE = UNSAFE.objectFieldOffset
1063                 (tk.getDeclaredField("threadLocalRandomProbe"));
1064             SECONDARY = UNSAFE.objectFieldOffset
1065                 (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
1066         } catch (Exception e) {
1067             throw new Error(e);
1068         }
1069     }
1070 }