ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
Revision: 1.12
Committed: Sun Jul 21 14:02:23 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.11: +29 -30 lines
Log Message:
Use SecureRandom initial default seed; misc wording updates

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4     *
5     * This code is free software; you can redistribute it and/or modify it
6     * under the terms of the GNU General Public License version 2 only, as
7     * published by the Free Software Foundation. Oracle designates this
8     * particular file as subject to the "Classpath" exception as provided
9     * by Oracle in the LICENSE file that accompanied this code.
10     *
11     * This code is distributed in the hope that it will be useful, but WITHOUT
12     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13     * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14     * version 2 for more details (a copy is included in the LICENSE file that
15     * accompanied this code).
16     *
17     * You should have received a copy of the GNU General Public License version
18     * 2 along with this work; if not, write to the Free Software Foundation,
19     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20     *
21     * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22     * or visit www.oracle.com if you need additional information or have any
23     * questions.
24     */
25    
26     package java.util;
27    
28 dl 1.12 import java.security.SecureRandom;
29 dl 1.1 import java.util.concurrent.atomic.AtomicLong;
30     import java.util.Spliterator;
31     import java.util.function.IntConsumer;
32     import java.util.function.LongConsumer;
33     import java.util.function.DoubleConsumer;
34     import java.util.stream.StreamSupport;
35     import java.util.stream.IntStream;
36     import java.util.stream.LongStream;
37     import java.util.stream.DoubleStream;
38    
39     /**
40     * A generator of uniform pseudorandom values applicable for use in
41     * (among other contexts) isolated parallel computations that may
42     * generate subtasks. Class SplittableRandom supports methods for
43 jsr166 1.3 * producing pseudorandom numbers of type {@code int}, {@code long},
44 dl 1.1 * and {@code double} with similar usages as for class
45 jsr166 1.9 * {@link java.util.Random} but differs in the following ways:
46     *
47     * <ul>
48 dl 1.1 *
49     * <li>Series of generated values pass the DieHarder suite testing
50     * independence and uniformity properties of random number generators.
51     * (Most recently validated with <a
52     * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
53     * 3.31.1</a>.) These tests validate only the methods for certain
54     * types and ranges, but similar properties are expected to hold, at
55 dl 1.11 * least approximately, for others as well. The <em>period</em>
56     * (length of any series of generated values before it repeats) is at
57     * least 2<sup>64</sup>. </li>
58 dl 1.1 *
59     * <li> Method {@link #split} constructs and returns a new
60     * SplittableRandom instance that shares no mutable state with the
61 dl 1.7 * current instance. However, with very high probability, the
62     * values collectively generated by the two objects have the same
63 dl 1.1 * statistical properties as if the same quantity of values were
64     * generated by a single thread using a single {@code
65     * SplittableRandom} object. </li>
66     *
67     * <li>Instances of SplittableRandom are <em>not</em> thread-safe.
68     * They are designed to be split, not shared, across threads. For
69     * example, a {@link java.util.concurrent.ForkJoinTask
70     * fork/join-style} computation using random numbers might include a
71     * construction of the form {@code new
72     * Subtask(aSplittableRandom.split()).fork()}.
73     *
74     * <li>This class provides additional methods for generating random
75     * streams, that employ the above techniques when used in {@code
76     * stream.parallel()} mode.</li>
77     *
78     * </ul>
79     *
80     * @author Guy Steele
81 dl 1.2 * @author Doug Lea
82 dl 1.1 * @since 1.8
83     */
84     public class SplittableRandom {
85    
86     /*
87     * File organization: First the non-public methods that constitute
88     * the main algorithm, then the main public methods, followed by
89     * some custom spliterator classes needed for stream methods.
90     *
91     * Credits: Primary algorithm and code by Guy Steele. Stream
92     * support methods by Doug Lea. Documentation jointly produced
93     * with additional help from Brian Goetz.
94     */
95    
96     /*
97     * Implementation Overview.
98     *
99     * This algorithm was inspired by the "DotMix" algorithm by
100     * Leiserson, Schardl, and Sukha "Deterministic Parallel
101     * Random-Number Generation for Dynamic-Multithreading Platforms",
102     * PPoPP 2012, but improves and extends it in several ways.
103     *
104 dl 1.7 * The primary update step (see method nextSeed()) is simply to
105     * add a constant ("gamma") to the current seed, modulo a prime
106     * ("George"). However, the nextLong and nextInt methods do not
107     * return this value, but instead the results of bit-mixing
108     * transformations that produce more uniformly distributed
109     * sequences.
110 dl 1.1 *
111     * "George" is the otherwise nameless (because it cannot be
112     * represented) prime number 2^64+13. Using a prime number larger
113     * than can fit in a long ensures that all possible long values
114     * can occur, plus 13 others that just get skipped over when they
115     * are encountered; see method addGammaModGeorge. For this to
116     * work, initial gamma values must be at least 13.
117     *
118     * The value of gamma differs for each instance across a series of
119     * splits, and is generated using a slightly stripped-down variant
120     * of the same algorithm, but operating across calls to split(),
121 dl 1.2 * not calls to nextSeed(): Each instance carries the state of
122 dl 1.1 * this generator as nextSplit, and uses mix64(nextSplit) as its
123     * own gamma value. Computations of gammas themselves use a fixed
124     * constant as the second argument to the addGammaModGeorge
125 dl 1.12 * function, GAMMA_GAMMA. The value of GAMMA_GAMMA is arbitrary
126     * (except must be at least 13), but because it serves as the base
127     * of split sequences, should be subject to validation of
128     * consequent random number quality metrics.
129 dl 1.1 *
130     * The mix64 bit-mixing function called by nextLong and other
131     * methods computes the same value as the "64-bit finalizer"
132     * function in Austin Appleby's MurmurHash3 algorithm. See
133     * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
134     * comments: "The constants for the finalizers were generated by a
135     * simple simulated-annealing algorithm, and both avalanche all
136     * bits of 'h' to within 0.25% bias." It also appears to work to
137     * use instead any of the variants proposed by David Stafford at
138     * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
139     * but these variants have not yet been tested as thoroughly
140     * in the context of the implementation of SplittableRandom.
141     *
142     * The mix32 function used for nextInt just consists of two of the
143     * five lines of mix64; avalanche testing shows that the 64-bit result
144     * has its top 32 bits avalanched well, though not the bottom 32 bits.
145     * DieHarder tests show that it is adequate for generating one
146     * random int from the 64-bit result of nextSeed.
147     *
148     * Support for the default (no-argument) constructor relies on an
149     * AtomicLong (defaultSeedGenerator) to help perform the
150     * equivalent of a split of a statically constructed
151     * SplittableRandom. Unlike other cases, this split must be
152     * performed in a thread-safe manner. We use
153     * AtomicLong.compareAndSet as the (typically) most efficient
154 dl 1.12 * mechanism. To bootstrap, we start off using a SecureRandom
155     * initial default seed, and update using a fixed
156     * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
157     * not 0, for its splitSeed argument (addGammaModGeorge(0,
158     * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
159     * this root generator, even though the root is not explicitly
160     * represented as a SplittableRandom.
161 dl 1.1 */
162    
163     /**
164 dl 1.12 * The value for producing new gamma values. Must be greater or
165     * equal to 13. Otherwise, the value is arbitrary subject to
166     * validation of the resulting statistical quality of splits.
167 dl 1.1 */
168     private static final long GAMMA_GAMMA = 0xF2281E2DBA6606F3L;
169    
170     /**
171 dl 1.12 * The seed update value for default constructors. Must be
172     * greater or equal to 13. Otherwise, the value is arbitrary.
173 dl 1.1 */
174     private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
175    
176     /**
177 dl 1.11 * The value 13 with 64bit sign bit set. Used in the signed
178     * comparison in addGammaModGeorge.
179     */
180     private static final long BOTTOM13 = 0x800000000000000DL;
181    
182     /**
183 dl 1.5 * The least non-zero value returned by nextDouble(). This value
184 dl 1.7 * is scaled by a random value of 53 bits to produce a result.
185 dl 1.5 */
186     private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
187    
188     /**
189 dl 1.1 * The next seed for default constructors.
190     */
191     private static final AtomicLong defaultSeedGenerator =
192 dl 1.12 new AtomicLong(getInitialDefaultSeed());
193 dl 1.1
194     /**
195     * The seed, updated only via method nextSeed.
196     */
197     private long seed;
198    
199     /**
200     * The constant value added to seed (mod George) on each update.
201     */
202     private final long gamma;
203    
204     /**
205     * The next seed to use for splits. Propagated using
206     * addGammaModGeorge across instances.
207     */
208     private final long nextSplit;
209    
210     /**
211     * Adds the given gamma value, g, to the given seed value s, mod
212     * George (2^64+13). We regard s and g as unsigned values
213     * (ranging from 0 to 2^64-1). We add g to s either once or twice
214     * (mod George) as necessary to produce an (unsigned) result less
215     * than 2^64. We require that g must be at least 13. This
216     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
217     * George < 2^64; thus we need only a conditional, not a loop,
218     * to be sure of getting a representable value.
219     *
220 dl 1.11 * Because Java comparison operators are signed, we implement this
221     * by conceptually offsetting seed values downwards by 2^63, so
222     * 0..13 is represented as Long.MIN_VALUE..BOTTOM13.
223     *
224     * @param s a seed value, viewed as a signed long
225 dl 1.1 * @param g a gamma value, 13 <= g (as unsigned)
226     */
227     private static long addGammaModGeorge(long s, long g) {
228     long p = s + g;
229 dl 1.11 return (p >= s) ? p : ((p >= BOTTOM13) ? p : p + g) - 13L;
230 dl 1.1 }
231    
232     /**
233     * Returns a bit-mixed transformation of its argument.
234     * See above for explanation.
235     */
236     private static long mix64(long z) {
237     z ^= (z >>> 33);
238     z *= 0xff51afd7ed558ccdL;
239     z ^= (z >>> 33);
240     z *= 0xc4ceb9fe1a85ec53L;
241     z ^= (z >>> 33);
242     return z;
243     }
244    
245     /**
246     * Returns a bit-mixed int transformation of its argument.
247     * See above for explanation.
248     */
249     private static int mix32(long z) {
250     z ^= (z >>> 33);
251     z *= 0xc4ceb9fe1a85ec53L;
252     return (int)(z >>> 32);
253     }
254    
255     /**
256 dl 1.7 * Internal constructor used by all other constructors and by
257     * method split. Establishes the initial seed for this instance,
258     * and uses the given splitSeed to establish gamma, as well as the
259     * nextSplit to use by this instance. The loop to skip ineligible
260     * gammas very rarely iterates, and does so at most 13 times.
261     */
262     private SplittableRandom(long seed, long splitSeed) {
263     this.seed = seed;
264     long s = splitSeed, g;
265     do { // ensure gamma >= 13, considered as an unsigned integer
266     s = addGammaModGeorge(s, GAMMA_GAMMA);
267     g = mix64(s);
268 dl 1.11 } while (g >= 0L && g < 13L);
269 dl 1.7 this.gamma = g;
270     this.nextSplit = s;
271     }
272    
273     /**
274     * Updates in-place and returns seed.
275     * See above for explanation.
276     */
277     private long nextSeed() {
278     return seed = addGammaModGeorge(seed, gamma);
279     }
280    
281     /**
282     * Atomically updates and returns next seed for default constructor.
283 dl 1.1 */
284     private static long nextDefaultSeed() {
285     long oldSeed, newSeed;
286     do {
287     oldSeed = defaultSeedGenerator.get();
288     newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
289     } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
290     return mix64(newSeed);
291     }
292    
293 dl 1.12 /**
294     * Returns an initial default seed.
295     */
296     private static long getInitialDefaultSeed() {
297     byte[] seedBytes = java.security.SecureRandom.getSeed(8);
298     long s = (long)(seedBytes[0]) & 0xffL;
299     for (int i = 1; i < 8; ++i)
300     s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
301     return s;
302     }
303    
304 dl 1.1 /*
305     * Internal versions of nextX methods used by streams, as well as
306     * the public nextX(origin, bound) methods. These exist mainly to
307     * avoid the need for multiple versions of stream spliterators
308     * across the different exported forms of streams.
309     */
310    
311     /**
312     * The form of nextLong used by LongStream Spliterators. If
313     * origin is greater than bound, acts as unbounded form of
314     * nextLong, else as bounded form.
315     *
316     * @param origin the least value, unless greater than bound
317     * @param bound the upper bound (exclusive), must not equal origin
318     * @return a pseudorandom value
319     */
320     final long internalNextLong(long origin, long bound) {
321     /*
322     * Four Cases:
323     *
324     * 1. If the arguments indicate unbounded form, act as
325     * nextLong().
326     *
327     * 2. If the range is an exact power of two, apply the
328     * associated bit mask.
329     *
330     * 3. If the range is positive, loop to avoid potential bias
331     * when the implicit nextLong() bound (2<sup>64</sup>) is not
332     * evenly divisible by the range. The loop rejects candidates
333     * computed from otherwise over-represented values. The
334     * expected number of iterations under an ideal generator
335 dl 1.4 * varies from 1 to 2, depending on the bound. The loop itself
336     * takes an unlovable form. Because the first candidate is
337     * already available, we need a break-in-the-middle
338     * construction, which is concisely but cryptically performed
339     * within the while-condition of a body-less for loop.
340 dl 1.1 *
341     * 4. Otherwise, the range cannot be represented as a positive
342 dl 1.4 * long. The loop repeatedly generates unbounded longs until
343     * obtaining a candidate meeting constraints (with an expected
344     * number of iterations of less than two).
345 dl 1.1 */
346    
347     long r = mix64(nextSeed());
348     if (origin < bound) {
349     long n = bound - origin, m = n - 1;
350 dl 1.7 if ((n & m) == 0L) // power of two
351 dl 1.1 r = (r & m) + origin;
352 dl 1.7 else if (n > 0L) { // reject over-represented candidates
353 dl 1.1 for (long u = r >>> 1; // ensure nonnegative
354 dl 1.7 u + m - (r = u % n) < 0L; // rejection check
355 dl 1.1 u = mix64(nextSeed()) >>> 1) // retry
356     ;
357     r += origin;
358     }
359 dl 1.7 else { // range not representable as long
360 dl 1.1 while (r < origin || r >= bound)
361     r = mix64(nextSeed());
362     }
363     }
364     return r;
365     }
366    
367     /**
368     * The form of nextInt used by IntStream Spliterators.
369     * Exactly the same as long version, except for types.
370     *
371     * @param origin the least value, unless greater than bound
372     * @param bound the upper bound (exclusive), must not equal origin
373     * @return a pseudorandom value
374     */
375     final int internalNextInt(int origin, int bound) {
376     int r = mix32(nextSeed());
377     if (origin < bound) {
378     int n = bound - origin, m = n - 1;
379     if ((n & m) == 0L)
380     r = (r & m) + origin;
381     else if (n > 0) {
382     for (int u = r >>> 1;
383 dl 1.7 u + m - (r = u % n) < 0;
384 dl 1.1 u = mix32(nextSeed()) >>> 1)
385     ;
386     r += origin;
387     }
388     else {
389     while (r < origin || r >= bound)
390     r = mix32(nextSeed());
391     }
392     }
393     return r;
394     }
395    
396     /**
397     * The form of nextDouble used by DoubleStream Spliterators.
398     *
399     * @param origin the least value, unless greater than bound
400     * @param bound the upper bound (exclusive), must not equal origin
401     * @return a pseudorandom value
402     */
403     final double internalNextDouble(double origin, double bound) {
404 dl 1.5 double r = (nextLong() >>> 11) * DOUBLE_UNIT;
405 dl 1.1 if (origin < bound) {
406     r = r * (bound - origin) + origin;
407 dl 1.7 if (r >= bound) // correct for rounding
408 dl 1.1 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
409     }
410     return r;
411     }
412    
413     /* ---------------- public methods ---------------- */
414    
415     /**
416 dl 1.7 * Creates a new SplittableRandom instance using the specified
417     * initial seed. SplittableRandom instances created with the same
418 dl 1.11 * seed in the same program generate identical sequences of values.
419 dl 1.1 *
420     * @param seed the initial seed
421     */
422     public SplittableRandom(long seed) {
423     this(seed, 0);
424     }
425    
426     /**
427     * Creates a new SplittableRandom instance that is likely to
428     * generate sequences of values that are statistically independent
429     * of those of any other instances in the current program; and
430     * may, and typically does, vary across program invocations.
431     */
432     public SplittableRandom() {
433     this(nextDefaultSeed(), GAMMA_GAMMA);
434     }
435    
436     /**
437     * Constructs and returns a new SplittableRandom instance that
438     * shares no mutable state with this instance. However, with very
439     * high probability, the set of values collectively generated by
440     * the two objects has the same statistical properties as if the
441     * same quantity of values were generated by a single thread using
442     * a single SplittableRandom object. Either or both of the two
443     * objects may be further split using the {@code split()} method,
444     * and the same expected statistical properties apply to the
445     * entire set of generators constructed by such recursive
446     * splitting.
447     *
448     * @return the new SplittableRandom instance
449     */
450     public SplittableRandom split() {
451     return new SplittableRandom(nextSeed(), nextSplit);
452     }
453    
454     /**
455     * Returns a pseudorandom {@code int} value.
456     *
457 dl 1.7 * @return a pseudorandom {@code int} value
458 dl 1.1 */
459     public int nextInt() {
460     return mix32(nextSeed());
461     }
462    
463     /**
464 dl 1.7 * Returns a pseudorandom {@code int} value between zero (inclusive)
465 dl 1.1 * and the specified bound (exclusive).
466     *
467     * @param bound the bound on the random number to be returned. Must be
468     * positive.
469 dl 1.7 * @return a pseudorandom {@code int} value between zero
470 jsr166 1.10 * (inclusive) and the bound (exclusive)
471 dl 1.7 * @throws IllegalArgumentException if the bound is less than zero
472 dl 1.1 */
473     public int nextInt(int bound) {
474     if (bound <= 0)
475     throw new IllegalArgumentException("bound must be positive");
476     // Specialize internalNextInt for origin 0
477     int r = mix32(nextSeed());
478     int m = bound - 1;
479     if ((bound & m) == 0L) // power of two
480     r &= m;
481     else { // reject over-represented candidates
482     for (int u = r >>> 1;
483 dl 1.7 u + m - (r = u % bound) < 0;
484 dl 1.1 u = mix32(nextSeed()) >>> 1)
485     ;
486     }
487     return r;
488     }
489    
490     /**
491     * Returns a pseudorandom {@code int} value between the specified
492     * origin (inclusive) and the specified bound (exclusive).
493     *
494     * @param origin the least value returned
495     * @param bound the upper bound (exclusive)
496     * @return a pseudorandom {@code int} value between the origin
497 jsr166 1.10 * (inclusive) and the bound (exclusive)
498 dl 1.7 * @throws IllegalArgumentException if {@code origin} is greater than
499 dl 1.1 * or equal to {@code bound}
500     */
501     public int nextInt(int origin, int bound) {
502     if (origin >= bound)
503     throw new IllegalArgumentException("bound must be greater than origin");
504     return internalNextInt(origin, bound);
505     }
506    
507     /**
508     * Returns a pseudorandom {@code long} value.
509     *
510 dl 1.7 * @return a pseudorandom {@code long} value
511 dl 1.1 */
512     public long nextLong() {
513     return mix64(nextSeed());
514     }
515    
516     /**
517 dl 1.7 * Returns a pseudorandom {@code long} value between zero (inclusive)
518 dl 1.1 * and the specified bound (exclusive).
519     *
520     * @param bound the bound on the random number to be returned. Must be
521     * positive.
522 dl 1.7 * @return a pseudorandom {@code long} value between zero
523 jsr166 1.10 * (inclusive) and the bound (exclusive)
524 dl 1.7 * @throws IllegalArgumentException if {@code bound} is less than zero
525 dl 1.1 */
526     public long nextLong(long bound) {
527     if (bound <= 0)
528     throw new IllegalArgumentException("bound must be positive");
529     // Specialize internalNextLong for origin 0
530     long r = mix64(nextSeed());
531     long m = bound - 1;
532     if ((bound & m) == 0L) // power of two
533     r &= m;
534     else { // reject over-represented candidates
535     for (long u = r >>> 1;
536     u + m - (r = u % bound) < 0L;
537     u = mix64(nextSeed()) >>> 1)
538     ;
539     }
540     return r;
541     }
542    
543     /**
544     * Returns a pseudorandom {@code long} value between the specified
545     * origin (inclusive) and the specified bound (exclusive).
546     *
547     * @param origin the least value returned
548     * @param bound the upper bound (exclusive)
549     * @return a pseudorandom {@code long} value between the origin
550 jsr166 1.10 * (inclusive) and the bound (exclusive)
551 dl 1.7 * @throws IllegalArgumentException if {@code origin} is greater than
552 dl 1.1 * or equal to {@code bound}
553     */
554     public long nextLong(long origin, long bound) {
555     if (origin >= bound)
556     throw new IllegalArgumentException("bound must be greater than origin");
557     return internalNextLong(origin, bound);
558     }
559    
560     /**
561 dl 1.7 * Returns a pseudorandom {@code double} value between zero
562     * (inclusive) and one (exclusive).
563 dl 1.1 *
564 dl 1.7 * @return a pseudorandom {@code double} value between zero
565     * (inclusive) and one (exclusive)
566 dl 1.1 */
567     public double nextDouble() {
568 dl 1.11 return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
569 dl 1.1 }
570    
571     /**
572     * Returns a pseudorandom {@code double} value between 0.0
573     * (inclusive) and the specified bound (exclusive).
574     *
575     * @param bound the bound on the random number to be returned. Must be
576     * positive.
577 dl 1.7 * @return a pseudorandom {@code double} value between zero
578 jsr166 1.10 * (inclusive) and the bound (exclusive)
579 dl 1.7 * @throws IllegalArgumentException if {@code bound} is less than zero
580 dl 1.1 */
581     public double nextDouble(double bound) {
582 dl 1.7 if (!(bound > 0.0))
583 dl 1.1 throw new IllegalArgumentException("bound must be positive");
584 dl 1.11 double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
585 dl 1.1 return (result < bound) ? result : // correct for rounding
586     Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
587     }
588    
589     /**
590 dl 1.7 * Returns a pseudorandom {@code double} value between the specified
591 dl 1.1 * origin (inclusive) and bound (exclusive).
592     *
593     * @param origin the least value returned
594     * @param bound the upper bound
595     * @return a pseudorandom {@code double} value between the origin
596 jsr166 1.10 * (inclusive) and the bound (exclusive)
597 dl 1.1 * @throws IllegalArgumentException if {@code origin} is greater than
598     * or equal to {@code bound}
599     */
600     public double nextDouble(double origin, double bound) {
601 dl 1.7 if (!(origin < bound))
602 dl 1.1 throw new IllegalArgumentException("bound must be greater than origin");
603     return internalNextDouble(origin, bound);
604     }
605    
606 dl 1.11 /**
607     * Returns a pseudorandom {@code boolean} value.
608     *
609     * @return a pseudorandom {@code boolean} value
610     */
611     public boolean nextBoolean() {
612     return mix32(nextSeed()) < 0;
613     }
614    
615 dl 1.1 // stream methods, coded in a way intended to better isolate for
616     // maintenance purposes the small differences across forms.
617    
618     /**
619 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
620 dl 1.1 * pseudorandom {@code int} values.
621     *
622     * @param streamSize the number of values to generate
623     * @return a stream of pseudorandom {@code int} values
624     * @throws IllegalArgumentException if {@code streamSize} is
625 dl 1.7 * less than zero
626 dl 1.1 */
627     public IntStream ints(long streamSize) {
628     if (streamSize < 0L)
629     throw new IllegalArgumentException("negative Stream size");
630     return StreamSupport.intStream
631     (new RandomIntsSpliterator
632     (this, 0L, streamSize, Integer.MAX_VALUE, 0),
633     false);
634     }
635    
636     /**
637     * Returns an effectively unlimited stream of pseudorandom {@code int}
638 jsr166 1.10 * values.
639 dl 1.1 *
640     * @implNote This method is implemented to be equivalent to {@code
641     * ints(Long.MAX_VALUE)}.
642     *
643     * @return a stream of pseudorandom {@code int} values
644     */
645     public IntStream ints() {
646     return StreamSupport.intStream
647     (new RandomIntsSpliterator
648     (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
649     false);
650     }
651    
652     /**
653 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
654 dl 1.1 * pseudorandom {@code int} values, each conforming to the given
655     * origin and bound.
656     *
657     * @param streamSize the number of values to generate
658     * @param randomNumberOrigin the origin of each random value
659     * @param randomNumberBound the bound of each random value
660     * @return a stream of pseudorandom {@code int} values,
661 jsr166 1.10 * each with the given origin and bound
662 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
663 dl 1.7 * less than zero, or {@code randomNumberOrigin}
664 dl 1.1 * is greater than or equal to {@code randomNumberBound}
665     */
666     public IntStream ints(long streamSize, int randomNumberOrigin,
667     int randomNumberBound) {
668     if (streamSize < 0L)
669     throw new IllegalArgumentException("negative Stream size");
670     if (randomNumberOrigin >= randomNumberBound)
671     throw new IllegalArgumentException("bound must be greater than origin");
672     return StreamSupport.intStream
673     (new RandomIntsSpliterator
674     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
675     false);
676     }
677    
678     /**
679     * Returns an effectively unlimited stream of pseudorandom {@code
680     * int} values, each conforming to the given origin and bound.
681     *
682     * @implNote This method is implemented to be equivalent to {@code
683     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
684     *
685     * @param randomNumberOrigin the origin of each random value
686     * @param randomNumberBound the bound of each random value
687     * @return a stream of pseudorandom {@code int} values,
688 jsr166 1.10 * each with the given origin and bound
689 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
690     * is greater than or equal to {@code randomNumberBound}
691     */
692     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
693     if (randomNumberOrigin >= randomNumberBound)
694     throw new IllegalArgumentException("bound must be greater than origin");
695     return StreamSupport.intStream
696     (new RandomIntsSpliterator
697     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
698     false);
699     }
700    
701     /**
702 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
703 dl 1.1 * pseudorandom {@code long} values.
704     *
705     * @param streamSize the number of values to generate
706 dl 1.7 * @return a stream of pseudorandom {@code long} values
707 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
708 dl 1.7 * less than zero
709 dl 1.1 */
710     public LongStream longs(long streamSize) {
711     if (streamSize < 0L)
712     throw new IllegalArgumentException("negative Stream size");
713     return StreamSupport.longStream
714     (new RandomLongsSpliterator
715     (this, 0L, streamSize, Long.MAX_VALUE, 0L),
716     false);
717     }
718    
719     /**
720     * Returns an effectively unlimited stream of pseudorandom {@code long}
721     * values.
722     *
723     * @implNote This method is implemented to be equivalent to {@code
724     * longs(Long.MAX_VALUE)}.
725     *
726     * @return a stream of pseudorandom {@code long} values
727     */
728     public LongStream longs() {
729     return StreamSupport.longStream
730     (new RandomLongsSpliterator
731     (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
732     false);
733     }
734    
735     /**
736 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
737 dl 1.1 * pseudorandom {@code long} values, each conforming to the
738     * given origin and bound.
739     *
740     * @param streamSize the number of values to generate
741     * @param randomNumberOrigin the origin of each random value
742     * @param randomNumberBound the bound of each random value
743     * @return a stream of pseudorandom {@code long} values,
744 jsr166 1.10 * each with the given origin and bound
745 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
746 dl 1.7 * less than zero, or {@code randomNumberOrigin}
747 dl 1.1 * is greater than or equal to {@code randomNumberBound}
748     */
749     public LongStream longs(long streamSize, long randomNumberOrigin,
750     long randomNumberBound) {
751     if (streamSize < 0L)
752     throw new IllegalArgumentException("negative Stream size");
753     if (randomNumberOrigin >= randomNumberBound)
754     throw new IllegalArgumentException("bound must be greater than origin");
755     return StreamSupport.longStream
756     (new RandomLongsSpliterator
757     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
758     false);
759     }
760    
761     /**
762     * Returns an effectively unlimited stream of pseudorandom {@code
763     * long} values, each conforming to the given origin and bound.
764     *
765     * @implNote This method is implemented to be equivalent to {@code
766     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
767     *
768     * @param randomNumberOrigin the origin of each random value
769     * @param randomNumberBound the bound of each random value
770     * @return a stream of pseudorandom {@code long} values,
771 jsr166 1.10 * each with the given origin and bound
772 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
773     * is greater than or equal to {@code randomNumberBound}
774     */
775     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
776     if (randomNumberOrigin >= randomNumberBound)
777     throw new IllegalArgumentException("bound must be greater than origin");
778     return StreamSupport.longStream
779     (new RandomLongsSpliterator
780     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
781     false);
782     }
783    
784     /**
785 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
786     * pseudorandom {@code double} values, each between zero
787     * (inclusive) and one (exclusive).
788 dl 1.1 *
789     * @param streamSize the number of values to generate
790     * @return a stream of {@code double} values
791     * @throws IllegalArgumentException if {@code streamSize} is
792 dl 1.7 * less than zero
793 dl 1.1 */
794     public DoubleStream doubles(long streamSize) {
795     if (streamSize < 0L)
796     throw new IllegalArgumentException("negative Stream size");
797     return StreamSupport.doubleStream
798     (new RandomDoublesSpliterator
799     (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
800     false);
801     }
802    
803     /**
804     * Returns an effectively unlimited stream of pseudorandom {@code
805 dl 1.7 * double} values, each between zero (inclusive) and one
806     * (exclusive).
807 dl 1.1 *
808     * @implNote This method is implemented to be equivalent to {@code
809     * doubles(Long.MAX_VALUE)}.
810     *
811     * @return a stream of pseudorandom {@code double} values
812     */
813     public DoubleStream doubles() {
814     return StreamSupport.doubleStream
815     (new RandomDoublesSpliterator
816     (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
817     false);
818     }
819    
820     /**
821 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
822 dl 1.1 * pseudorandom {@code double} values, each conforming to the
823     * given origin and bound.
824     *
825     * @param streamSize the number of values to generate
826     * @param randomNumberOrigin the origin of each random value
827     * @param randomNumberBound the bound of each random value
828     * @return a stream of pseudorandom {@code double} values,
829 jsr166 1.10 * each with the given origin and bound
830 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
831 jsr166 1.10 * less than zero
832 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
833     * is greater than or equal to {@code randomNumberBound}
834     */
835     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
836     double randomNumberBound) {
837     if (streamSize < 0L)
838     throw new IllegalArgumentException("negative Stream size");
839 dl 1.7 if (!(randomNumberOrigin < randomNumberBound))
840 dl 1.1 throw new IllegalArgumentException("bound must be greater than origin");
841     return StreamSupport.doubleStream
842     (new RandomDoublesSpliterator
843     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
844     false);
845     }
846    
847     /**
848     * Returns an effectively unlimited stream of pseudorandom {@code
849     * double} values, each conforming to the given origin and bound.
850     *
851     * @implNote This method is implemented to be equivalent to {@code
852     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
853     *
854     * @param randomNumberOrigin the origin of each random value
855     * @param randomNumberBound the bound of each random value
856     * @return a stream of pseudorandom {@code double} values,
857 jsr166 1.10 * each with the given origin and bound
858 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
859     * is greater than or equal to {@code randomNumberBound}
860     */
861     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
862 dl 1.7 if (!(randomNumberOrigin < randomNumberBound))
863 dl 1.1 throw new IllegalArgumentException("bound must be greater than origin");
864     return StreamSupport.doubleStream
865     (new RandomDoublesSpliterator
866     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
867     false);
868     }
869    
870     /**
871     * Spliterator for int streams. We multiplex the four int
872 dl 1.7 * versions into one class by treating a bound less than origin as
873 dl 1.1 * unbounded, and also by treating "infinite" as equivalent to
874     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
875     * approach. The long and double versions of this class are
876     * identical except for types.
877     */
878 dl 1.11 static final class RandomIntsSpliterator implements Spliterator.OfInt {
879 dl 1.1 final SplittableRandom rng;
880     long index;
881     final long fence;
882     final int origin;
883     final int bound;
884     RandomIntsSpliterator(SplittableRandom rng, long index, long fence,
885     int origin, int bound) {
886     this.rng = rng; this.index = index; this.fence = fence;
887     this.origin = origin; this.bound = bound;
888     }
889    
890     public RandomIntsSpliterator trySplit() {
891     long i = index, m = (i + fence) >>> 1;
892     return (m <= i) ? null :
893     new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound);
894     }
895    
896     public long estimateSize() {
897     return fence - index;
898     }
899    
900     public int characteristics() {
901     return (Spliterator.SIZED | Spliterator.SUBSIZED |
902 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
903 dl 1.1 }
904    
905     public boolean tryAdvance(IntConsumer consumer) {
906     if (consumer == null) throw new NullPointerException();
907     long i = index, f = fence;
908     if (i < f) {
909     consumer.accept(rng.internalNextInt(origin, bound));
910     index = i + 1;
911     return true;
912     }
913     return false;
914     }
915    
916     public void forEachRemaining(IntConsumer consumer) {
917     if (consumer == null) throw new NullPointerException();
918     long i = index, f = fence;
919     if (i < f) {
920     index = f;
921     int o = origin, b = bound;
922     do {
923     consumer.accept(rng.internalNextInt(o, b));
924     } while (++i < f);
925     }
926     }
927     }
928    
929     /**
930     * Spliterator for long streams.
931     */
932 dl 1.11 static final class RandomLongsSpliterator implements Spliterator.OfLong {
933 dl 1.1 final SplittableRandom rng;
934     long index;
935     final long fence;
936     final long origin;
937     final long bound;
938     RandomLongsSpliterator(SplittableRandom rng, long index, long fence,
939     long origin, long bound) {
940     this.rng = rng; this.index = index; this.fence = fence;
941     this.origin = origin; this.bound = bound;
942     }
943    
944     public RandomLongsSpliterator trySplit() {
945     long i = index, m = (i + fence) >>> 1;
946     return (m <= i) ? null :
947     new RandomLongsSpliterator(rng.split(), i, index = m, origin, bound);
948     }
949    
950     public long estimateSize() {
951     return fence - index;
952     }
953    
954     public int characteristics() {
955     return (Spliterator.SIZED | Spliterator.SUBSIZED |
956 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
957 dl 1.1 }
958    
959     public boolean tryAdvance(LongConsumer consumer) {
960     if (consumer == null) throw new NullPointerException();
961     long i = index, f = fence;
962     if (i < f) {
963     consumer.accept(rng.internalNextLong(origin, bound));
964     index = i + 1;
965     return true;
966     }
967     return false;
968     }
969    
970     public void forEachRemaining(LongConsumer consumer) {
971     if (consumer == null) throw new NullPointerException();
972     long i = index, f = fence;
973     if (i < f) {
974     index = f;
975     long o = origin, b = bound;
976     do {
977     consumer.accept(rng.internalNextLong(o, b));
978     } while (++i < f);
979     }
980     }
981    
982     }
983    
984     /**
985     * Spliterator for double streams.
986     */
987 dl 1.11 static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
988 dl 1.1 final SplittableRandom rng;
989     long index;
990     final long fence;
991     final double origin;
992     final double bound;
993     RandomDoublesSpliterator(SplittableRandom rng, long index, long fence,
994     double origin, double bound) {
995     this.rng = rng; this.index = index; this.fence = fence;
996     this.origin = origin; this.bound = bound;
997     }
998    
999     public RandomDoublesSpliterator trySplit() {
1000     long i = index, m = (i + fence) >>> 1;
1001     return (m <= i) ? null :
1002     new RandomDoublesSpliterator(rng.split(), i, index = m, origin, bound);
1003     }
1004    
1005     public long estimateSize() {
1006     return fence - index;
1007     }
1008    
1009     public int characteristics() {
1010     return (Spliterator.SIZED | Spliterator.SUBSIZED |
1011 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
1012 dl 1.1 }
1013    
1014     public boolean tryAdvance(DoubleConsumer consumer) {
1015     if (consumer == null) throw new NullPointerException();
1016     long i = index, f = fence;
1017     if (i < f) {
1018     consumer.accept(rng.internalNextDouble(origin, bound));
1019     index = i + 1;
1020     return true;
1021     }
1022     return false;
1023     }
1024    
1025     public void forEachRemaining(DoubleConsumer consumer) {
1026     if (consumer == null) throw new NullPointerException();
1027     long i = index, f = fence;
1028     if (i < f) {
1029     index = f;
1030     double o = origin, b = bound;
1031     do {
1032     consumer.accept(rng.internalNextDouble(o, b));
1033     } while (++i < f);
1034     }
1035     }
1036     }
1037    
1038     }