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
36package java.util.concurrent;
37
38import java.io.ObjectStreamField;
39import java.util.Random;
40import java.util.Spliterator;
41import java.util.concurrent.atomic.AtomicInteger;
42import java.util.concurrent.atomic.AtomicLong;
43import java.util.function.DoubleConsumer;
44import java.util.function.IntConsumer;
45import java.util.function.LongConsumer;
46import java.util.stream.DoubleStream;
47import java.util.stream.IntStream;
48import java.util.stream.LongStream;
49import 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 */
82public 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
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
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 */
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     */
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     */
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     */
183    public void setSeed(long seed) {
184        // only allow call from super() constructor
185        if (initialized)
186            throw new UnsupportedOperationException();
187    }
188
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.
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
440    public float nextFloat() {
441        return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
442    }
443
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     * Returns a stream producing the given {@code streamSize} number of
466     * pseudorandom {@code int} values.
467     *
468     * @param streamSize the number of values to generate
469     * @return a stream of pseudorandom {@code int} values
470     * @throws IllegalArgumentException if {@code streamSize} is
471     *         less than zero
472     * @since 1.8
473     */
474    public IntStream ints(long streamSize) {
475        if (streamSize < 0L)
476            throw new IllegalArgumentException(BAD_SIZE);
477        return StreamSupport.intStream
478            (new RandomIntsSpliterator
479             (0L, streamSize, Integer.MAX_VALUE, 0),
480             false);
481    }
482
483    /**
484     * Returns an effectively unlimited stream of pseudorandom {@code int}
485     * values.
486     *
487     * @implNote This method is implemented to be equivalent to {@code
488     * ints(Long.MAX_VALUE)}.
489     *
490     * @return a stream of pseudorandom {@code int} values
491     * @since 1.8
492     */
493    public IntStream ints() {
494        return StreamSupport.intStream
495            (new RandomIntsSpliterator
496             (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
497             false);
498    }
499
500    /**
501     * Returns a stream producing the given {@code streamSize} number
502     * of pseudorandom {@code int} values, each conforming to the given
503     * origin (inclusive) and bound (exclusive).
504     *
505     * @param streamSize the number of values to generate
506     * @param randomNumberOrigin the origin (inclusive) of each random value
507     * @param randomNumberBound the bound (exclusive) of each random value
508     * @return a stream of pseudorandom {@code int} values,
509     *         each with the given origin (inclusive) and bound (exclusive)
510     * @throws IllegalArgumentException if {@code streamSize} is
511     *         less than zero, or {@code randomNumberOrigin}
512     *         is greater than or equal to {@code randomNumberBound}
513     * @since 1.8
514     */
515    public IntStream ints(long streamSize, int randomNumberOrigin,
516                          int randomNumberBound) {
517        if (streamSize < 0L)
518            throw new IllegalArgumentException(BAD_SIZE);
519        if (randomNumberOrigin >= randomNumberBound)
520            throw new IllegalArgumentException(BAD_RANGE);
521        return StreamSupport.intStream
522            (new RandomIntsSpliterator
523             (0L, streamSize, randomNumberOrigin, randomNumberBound),
524             false);
525    }
526
527    /**
528     * Returns an effectively unlimited stream of pseudorandom {@code
529     * int} values, each conforming to the given origin (inclusive) and bound
530     * (exclusive).
531     *
532     * @implNote This method is implemented to be equivalent to {@code
533     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
534     *
535     * @param randomNumberOrigin the origin (inclusive) of each random value
536     * @param randomNumberBound the bound (exclusive) of each random value
537     * @return a stream of pseudorandom {@code int} values,
538     *         each with the given origin (inclusive) and bound (exclusive)
539     * @throws IllegalArgumentException if {@code randomNumberOrigin}
540     *         is greater than or equal to {@code randomNumberBound}
541     * @since 1.8
542     */
543    public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
544        if (randomNumberOrigin >= randomNumberBound)
545            throw new IllegalArgumentException(BAD_RANGE);
546        return StreamSupport.intStream
547            (new RandomIntsSpliterator
548             (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
549             false);
550    }
551
552    /**
553     * Returns a stream producing the given {@code streamSize} number of
554     * pseudorandom {@code long} values.
555     *
556     * @param streamSize the number of values to generate
557     * @return a stream of pseudorandom {@code long} values
558     * @throws IllegalArgumentException if {@code streamSize} is
559     *         less than zero
560     * @since 1.8
561     */
562    public LongStream longs(long streamSize) {
563        if (streamSize < 0L)
564            throw new IllegalArgumentException(BAD_SIZE);
565        return StreamSupport.longStream
566            (new RandomLongsSpliterator
567             (0L, streamSize, Long.MAX_VALUE, 0L),
568             false);
569    }
570
571    /**
572     * Returns an effectively unlimited stream of pseudorandom {@code long}
573     * values.
574     *
575     * @implNote This method is implemented to be equivalent to {@code
576     * longs(Long.MAX_VALUE)}.
577     *
578     * @return a stream of pseudorandom {@code long} values
579     * @since 1.8
580     */
581    public LongStream longs() {
582        return StreamSupport.longStream
583            (new RandomLongsSpliterator
584             (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
585             false);
586    }
587
588    /**
589     * Returns a stream producing the given {@code streamSize} number of
590     * pseudorandom {@code long}, each conforming to the given origin
591     * (inclusive) and bound (exclusive).
592     *
593     * @param streamSize the number of values to generate
594     * @param randomNumberOrigin the origin (inclusive) of each random value
595     * @param randomNumberBound the bound (exclusive) of each random value
596     * @return a stream of pseudorandom {@code long} values,
597     *         each with the given origin (inclusive) and bound (exclusive)
598     * @throws IllegalArgumentException if {@code streamSize} is
599     *         less than zero, or {@code randomNumberOrigin}
600     *         is greater than or equal to {@code randomNumberBound}
601     * @since 1.8
602     */
603    public LongStream longs(long streamSize, long randomNumberOrigin,
604                            long randomNumberBound) {
605        if (streamSize < 0L)
606            throw new IllegalArgumentException(BAD_SIZE);
607        if (randomNumberOrigin >= randomNumberBound)
608            throw new IllegalArgumentException(BAD_RANGE);
609        return StreamSupport.longStream
610            (new RandomLongsSpliterator
611             (0L, streamSize, randomNumberOrigin, randomNumberBound),
612             false);
613    }
614
615    /**
616     * Returns an effectively unlimited stream of pseudorandom {@code
617     * long} values, each conforming to the given origin (inclusive) and bound
618     * (exclusive).
619     *
620     * @implNote This method is implemented to be equivalent to {@code
621     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
622     *
623     * @param randomNumberOrigin the origin (inclusive) of each random value
624     * @param randomNumberBound the bound (exclusive) of each random value
625     * @return a stream of pseudorandom {@code long} values,
626     *         each with the given origin (inclusive) and bound (exclusive)
627     * @throws IllegalArgumentException if {@code randomNumberOrigin}
628     *         is greater than or equal to {@code randomNumberBound}
629     * @since 1.8
630     */
631    public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
632        if (randomNumberOrigin >= randomNumberBound)
633            throw new IllegalArgumentException(BAD_RANGE);
634        return StreamSupport.longStream
635            (new RandomLongsSpliterator
636             (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
637             false);
638    }
639
640    /**
641     * Returns a stream producing the given {@code streamSize} number of
642     * pseudorandom {@code double} values, each between zero
643     * (inclusive) and one (exclusive).
644     *
645     * @param streamSize the number of values to generate
646     * @return a stream of {@code double} values
647     * @throws IllegalArgumentException if {@code streamSize} is
648     *         less than zero
649     * @since 1.8
650     */
651    public DoubleStream doubles(long streamSize) {
652        if (streamSize < 0L)
653            throw new IllegalArgumentException(BAD_SIZE);
654        return StreamSupport.doubleStream
655            (new RandomDoublesSpliterator
656             (0L, streamSize, Double.MAX_VALUE, 0.0),
657             false);
658    }
659
660    /**
661     * Returns an effectively unlimited stream of pseudorandom {@code
662     * double} values, each between zero (inclusive) and one
663     * (exclusive).
664     *
665     * @implNote This method is implemented to be equivalent to {@code
666     * doubles(Long.MAX_VALUE)}.
667     *
668     * @return a stream of pseudorandom {@code double} values
669     * @since 1.8
670     */
671    public DoubleStream doubles() {
672        return StreamSupport.doubleStream
673            (new RandomDoublesSpliterator
674             (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
675             false);
676    }
677
678    /**
679     * Returns a stream producing the given {@code streamSize} number of
680     * pseudorandom {@code double} values, each conforming to the given origin
681     * (inclusive) and bound (exclusive).
682     *
683     * @param streamSize the number of values to generate
684     * @param randomNumberOrigin the origin (inclusive) of each random value
685     * @param randomNumberBound the bound (exclusive) of each random value
686     * @return a stream of pseudorandom {@code double} values,
687     *         each with the given origin (inclusive) and bound (exclusive)
688     * @throws IllegalArgumentException if {@code streamSize} is
689     *         less than zero
690     * @throws IllegalArgumentException if {@code randomNumberOrigin}
691     *         is greater than or equal to {@code randomNumberBound}
692     * @since 1.8
693     */
694    public DoubleStream doubles(long streamSize, double randomNumberOrigin,
695                                double randomNumberBound) {
696        if (streamSize < 0L)
697            throw new IllegalArgumentException(BAD_SIZE);
698        if (!(randomNumberOrigin < randomNumberBound))
699            throw new IllegalArgumentException(BAD_RANGE);
700        return StreamSupport.doubleStream
701            (new RandomDoublesSpliterator
702             (0L, streamSize, randomNumberOrigin, randomNumberBound),
703             false);
704    }
705
706    /**
707     * Returns an effectively unlimited stream of pseudorandom {@code
708     * double} values, each conforming to the given origin (inclusive) and bound
709     * (exclusive).
710     *
711     * @implNote This method is implemented to be equivalent to {@code
712     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
713     *
714     * @param randomNumberOrigin the origin (inclusive) of each random value
715     * @param randomNumberBound the bound (exclusive) of each random value
716     * @return a stream of pseudorandom {@code double} values,
717     *         each with the given origin (inclusive) and bound (exclusive)
718     * @throws IllegalArgumentException if {@code randomNumberOrigin}
719     *         is greater than or equal to {@code randomNumberBound}
720     * @since 1.8
721     */
722    public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
723        if (!(randomNumberOrigin < randomNumberBound))
724            throw new IllegalArgumentException(BAD_RANGE);
725        return StreamSupport.doubleStream
726            (new RandomDoublesSpliterator
727             (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
728             false);
729    }
730
731    /**
732     * Spliterator for int streams.  We multiplex the four int
733     * versions into one class by treating a bound less than origin as
734     * unbounded, and also by treating "infinite" as equivalent to
735     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
736     * approach. The long and double versions of this class are
737     * identical except for types.
738     */
739    private static final class RandomIntsSpliterator
740            implements Spliterator.OfInt {
741        long index;
742        final long fence;
743        final int origin;
744        final int bound;
745        RandomIntsSpliterator(long index, long fence,
746                              int origin, int bound) {
747            this.index = index; this.fence = fence;
748            this.origin = origin; this.bound = bound;
749        }
750
751        public RandomIntsSpliterator trySplit() {
752            long i = index, m = (i + fence) >>> 1;
753            return (m <= i) ? null :
754                new RandomIntsSpliterator(i, index = m, origin, bound);
755        }
756
757        public long estimateSize() {
758            return fence - index;
759        }
760
761        public int characteristics() {
762            return (Spliterator.SIZED | Spliterator.SUBSIZED |
763                    Spliterator.NONNULL | Spliterator.IMMUTABLE);
764        }
765
766        public boolean tryAdvance(IntConsumer consumer) {
767            if (consumer == null) throw new NullPointerException();
768            long i = index, f = fence;
769            if (i < f) {
770                consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
771                index = i + 1;
772                return true;
773            }
774            return false;
775        }
776
777        public void forEachRemaining(IntConsumer consumer) {
778            if (consumer == null) throw new NullPointerException();
779            long i = index, f = fence;
780            if (i < f) {
781                index = f;
782                int o = origin, b = bound;
783                ThreadLocalRandom rng = ThreadLocalRandom.current();
784                do {
785                    consumer.accept(rng.internalNextInt(o, b));
786                } while (++i < f);
787            }
788        }
789    }
790
791    /**
792     * Spliterator for long streams.
793     */
794    private static final class RandomLongsSpliterator
795            implements Spliterator.OfLong {
796        long index;
797        final long fence;
798        final long origin;
799        final long bound;
800        RandomLongsSpliterator(long index, long fence,
801                               long origin, long bound) {
802            this.index = index; this.fence = fence;
803            this.origin = origin; this.bound = bound;
804        }
805
806        public RandomLongsSpliterator trySplit() {
807            long i = index, m = (i + fence) >>> 1;
808            return (m <= i) ? null :
809                new RandomLongsSpliterator(i, index = m, origin, bound);
810        }
811
812        public long estimateSize() {
813            return fence - index;
814        }
815
816        public int characteristics() {
817            return (Spliterator.SIZED | Spliterator.SUBSIZED |
818                    Spliterator.NONNULL | Spliterator.IMMUTABLE);
819        }
820
821        public boolean tryAdvance(LongConsumer consumer) {
822            if (consumer == null) throw new NullPointerException();
823            long i = index, f = fence;
824            if (i < f) {
825                consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
826                index = i + 1;
827                return true;
828            }
829            return false;
830        }
831
832        public void forEachRemaining(LongConsumer consumer) {
833            if (consumer == null) throw new NullPointerException();
834            long i = index, f = fence;
835            if (i < f) {
836                index = f;
837                long o = origin, b = bound;
838                ThreadLocalRandom rng = ThreadLocalRandom.current();
839                do {
840                    consumer.accept(rng.internalNextLong(o, b));
841                } while (++i < f);
842            }
843        }
844
845    }
846
847    /**
848     * Spliterator for double streams.
849     */
850    private static final class RandomDoublesSpliterator
851            implements Spliterator.OfDouble {
852        long index;
853        final long fence;
854        final double origin;
855        final double bound;
856        RandomDoublesSpliterator(long index, long fence,
857                                 double origin, double bound) {
858            this.index = index; this.fence = fence;
859            this.origin = origin; this.bound = bound;
860        }
861
862        public RandomDoublesSpliterator trySplit() {
863            long i = index, m = (i + fence) >>> 1;
864            return (m <= i) ? null :
865                new RandomDoublesSpliterator(i, index = m, origin, bound);
866        }
867
868        public long estimateSize() {
869            return fence - index;
870        }
871
872        public int characteristics() {
873            return (Spliterator.SIZED | Spliterator.SUBSIZED |
874                    Spliterator.NONNULL | Spliterator.IMMUTABLE);
875        }
876
877        public boolean tryAdvance(DoubleConsumer consumer) {
878            if (consumer == null) throw new NullPointerException();
879            long i = index, f = fence;
880            if (i < f) {
881                consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
882                index = i + 1;
883                return true;
884            }
885            return false;
886        }
887
888        public void forEachRemaining(DoubleConsumer consumer) {
889            if (consumer == null) throw new NullPointerException();
890            long i = index, f = fence;
891            if (i < f) {
892                index = f;
893                double o = origin, b = bound;
894                ThreadLocalRandom rng = ThreadLocalRandom.current();
895                do {
896                    consumer.accept(rng.internalNextDouble(o, b));
897                } while (++i < f);
898            }
899        }
900    }
901
902
903    // Within-package utilities
904
905    /*
906     * Descriptions of the usages of the methods below can be found in
907     * the classes that use them. Briefly, a thread's "probe" value is
908     * a non-zero hash code that (probably) does not collide with
909     * other existing threads with respect to any power of two
910     * collision space. When it does collide, it is pseudo-randomly
911     * adjusted (using a Marsaglia XorShift). The nextSecondarySeed
912     * method is used in the same contexts as ThreadLocalRandom, but
913     * only for transient usages such as random adaptive spin/block
914     * sequences for which a cheap RNG suffices and for which it could
915     * in principle disrupt user-visible statistical properties of the
916     * main ThreadLocalRandom if we were to use it.
917     *
918     * Note: Because of package-protection issues, versions of some
919     * these methods also appear in some subpackage classes.
920     */
921
922    /**
923     * Returns the probe value for the current thread without forcing
924     * initialization. Note that invoking ThreadLocalRandom.current()
925     * can be used to force initialization on zero return.
926     */
927    static final int getProbe() {
928        return U.getInt(Thread.currentThread(), PROBE);
929    }
930
931    /**
932     * Pseudo-randomly advances and records the given probe value for the
933     * given thread.
934     */
935    static final int advanceProbe(int probe) {
936        probe ^= probe << 13;   // xorshift
937        probe ^= probe >>> 17;
938        probe ^= probe << 5;
939        U.putInt(Thread.currentThread(), PROBE, probe);
940        return probe;
941    }
942
943    /**
944     * Returns the pseudo-randomly initialized or updated secondary seed.
945     */
946    static final int nextSecondarySeed() {
947        int r;
948        Thread t = Thread.currentThread();
949        if ((r = U.getInt(t, SECONDARY)) != 0) {
950            r ^= r << 13;   // xorshift
951            r ^= r >>> 17;
952            r ^= r << 5;
953        }
954        else if ((r = mix32(seeder.getAndAdd(SEEDER_INCREMENT))) == 0)
955            r = 1; // avoid zero
956        U.putInt(t, SECONDARY, r);
957        return r;
958    }
959
960    // Serialization support
961
962    private static final long serialVersionUID = -5851777807851030925L;
963
964    /**
965     * @serialField rnd long
966     *              seed for random computations
967     * @serialField initialized boolean
968     *              always true
969     */
970    private static final ObjectStreamField[] serialPersistentFields = {
971        new ObjectStreamField("rnd", long.class),
972        new ObjectStreamField("initialized", boolean.class),
973    };
974
975    /**
976     * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
977     * @param s the stream
978     * @throws java.io.IOException if an I/O error occurs
979     */
980    private void writeObject(java.io.ObjectOutputStream s)
981        throws java.io.IOException {
982
983        java.io.ObjectOutputStream.PutField fields = s.putFields();
984        fields.put("rnd", U.getLong(Thread.currentThread(), SEED));
985        fields.put("initialized", true);
986        s.writeFields();
987    }
988
989    /**
990     * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}.
991     * @return the {@link #current() current} thread's {@code ThreadLocalRandom}
992     */
993    private Object readResolve() {
994        return current();
995    }
996
997    // Static initialization
998
999    /**
1000     * The seed increment.
1001     */
1002    private static final long GAMMA = 0x9e3779b97f4a7c15L;
1003
1004    /**
1005     * The increment for generating probe values.
1006     */
1007    private static final int PROBE_INCREMENT = 0x9e3779b9;
1008
1009    /**
1010     * The increment of seeder per new instance.
1011     */
1012    private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
1013
1014    // Constants from SplittableRandom
1015    private static final double DOUBLE_UNIT = 0x1.0p-53;  // 1.0  / (1L << 53)
1016    private static final float  FLOAT_UNIT  = 0x1.0p-24f; // 1.0f / (1 << 24)
1017
1018    // IllegalArgumentException messages
1019    static final String BAD_BOUND = "bound must be positive";
1020    static final String BAD_RANGE = "bound must be greater than origin";
1021    static final String BAD_SIZE  = "size must be non-negative";
1022
1023    // Unsafe mechanics
1024    private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1025    private static final long SEED;
1026    private static final long PROBE;
1027    private static final long SECONDARY;
1028    static {
1029        try {
1030            SEED = U.objectFieldOffset
1031                (Thread.class.getDeclaredField("threadLocalRandomSeed"));
1032            PROBE = U.objectFieldOffset
1033                (Thread.class.getDeclaredField("threadLocalRandomProbe"));
1034            SECONDARY = U.objectFieldOffset
1035                (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed"));
1036        } catch (ReflectiveOperationException e) {
1037            throw new Error(e);
1038        }
1039    }
1040
1041    /** Rarely-used holder for the second of a pair of Gaussians */
1042    private static final ThreadLocal<Double> nextLocalGaussian =
1043        new ThreadLocal<>();
1044
1045    /** Generates per-thread initialization/probe field */
1046    private static final AtomicInteger probeGenerator = new AtomicInteger();
1047
1048    /** The common ThreadLocalRandom */
1049    static final ThreadLocalRandom instance = new ThreadLocalRandom();
1050
1051    /**
1052     * The next seed for default constructors.
1053     */
1054    private static final AtomicLong seeder
1055        = new AtomicLong(mix64(System.currentTimeMillis()) ^
1056                         mix64(System.nanoTime()));
1057
1058    // at end of <clinit> to survive static initialization circularity
1059    static {
1060        if (java.security.AccessController.doPrivileged(
1061            new java.security.PrivilegedAction<Boolean>() {
1062                public Boolean run() {
1063                    return Boolean.getBoolean("java.util.secureRandomSeed");
1064                }})) {
1065            byte[] seedBytes = java.security.SecureRandom.getSeed(8);
1066            long s = (long)seedBytes[0] & 0xffL;
1067            for (int i = 1; i < 8; ++i)
1068                s = (s << 8) | ((long)seedBytes[i] & 0xffL);
1069            seeder.set(s);
1070        }
1071    }
1072}
1073