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