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