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