ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
(Generate patch)

Comparing jsr166/src/main/java/util/SplittableRandom.java (file contents):
Revision 1.13 by dl, Thu Jul 25 13:19:09 2013 UTC vs.
Revision 1.18 by dl, Thu Aug 22 23:36:06 2013 UTC

# Line 26 | Line 26
26   package java.util;
27  
28   import java.security.SecureRandom;
29 + import java.net.InetAddress;
30   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;
# Line 39 | Line 39 | import java.util.stream.DoubleStream;
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
42 > * generate subtasks. Class {@code SplittableRandom} supports methods for
43   * producing pseudorandom numbers of type {@code int}, {@code long},
44   * and {@code double} with similar usages as for class
45   * {@link java.util.Random} but differs in the following ways:
# Line 77 | Line 77 | import java.util.stream.DoubleStream;
77   *
78   * </ul>
79   *
80 + * <p>Instances of {@code SplittableRandom} are not cryptographically
81 + * secure.  Consider instead using {@link java.security.SecureRandom}
82 + * in security-sensitive applications. Additionally,
83 + * default-constructed instances do not use a cryptographically random
84 + * seed unless the {@linkplain System#getProperty system property}
85 + * {@code java.util.secureRandomSeed} is set to {@code true}.
86 +
87 + *
88   * @author  Guy Steele
89   * @author  Doug Lea
90   * @since   1.8
# Line 84 | Line 92 | import java.util.stream.DoubleStream;
92   public class SplittableRandom {
93  
94      /*
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    /*
95       * Implementation Overview.
96       *
97       * This algorithm was inspired by the "DotMix" algorithm by
98       * Leiserson, Schardl, and Sukha "Deterministic Parallel
99       * Random-Number Generation for Dynamic-Multithreading Platforms",
100 <     * PPoPP 2012, but improves and extends it in several ways.
101 <     *
102 <     * The primary update step (see method nextSeed()) is simply to
103 <     * add a constant ("gamma") to the current seed, modulo a prime
104 <     * ("George"). However, the nextLong and nextInt methods do not
105 <     * return this value, but instead the results of bit-mixing
106 <     * transformations that produce more uniformly distributed
107 <     * sequences.
108 <     *
109 <     * "George" is the otherwise nameless (because it cannot be
110 <     * represented) prime number 2^64+13. Using a prime number larger
111 <     * than can fit in a long ensures that all possible long values
112 <     * can occur, plus 13 others that just get skipped over when they
113 <     * are encountered; see method addGammaModGeorge. For this to
114 <     * work, initial gamma values must be at least 13.
117 <     *
118 <     * The mix64 bit-mixing function called by nextLong and other
119 <     * methods computes the same value as the "64-bit finalizer"
120 <     * function in Austin Appleby's MurmurHash3 algorithm.  See
100 >     * PPoPP 2012, as well as those in "Parallel random numbers: as
101 >     * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011.  It
102 >     * differs mainly in simplifying and cheapening operations.
103 >     *
104 >     * The primary update step (method nextSeed()) is to add a
105 >     * constant ("gamma") to the current (64 bit) seed, forming a
106 >     * simple sequence.  The seed and the gamma values for any two
107 >     * SplittableRandom instances are highly likely to be different.
108 >     *
109 >     * Methods nextLong, nextInt, and derivatives do not return the
110 >     * sequence (seed) values, but instead a hash-like bit-mix of
111 >     * their bits, producing more independently distributed sequences.
112 >     * For nextLong, the mix64 bit-mixing function computes the same
113 >     * value as the "64-bit finalizer" function in Austin Appleby's
114 >     * MurmurHash3 algorithm.  See
115       * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
116       * comments: "The constants for the finalizers were generated by a
117       * simple simulated-annealing algorithm, and both avalanche all
118 <     * bits of 'h' to within 0.25% bias."
119 <     *
120 <     * The value of gamma differs for each instance across a series of
121 <     * splits, and is generated using an independent variant of the
122 <     * same algorithm, but operating across calls to split(), not
123 <     * calls to nextSeed(): Each instance carries the state of this
124 <     * generator as nextSplit. Gammas are treated as 57bit values,
125 <     * advancing by adding GAMMA_GAMMA mod GAMMA_PRIME, and bit-mixed
126 <     * with a 57-bit version of mix, using the "Mix01" multiplicative
127 <     * constants for MurmurHash3 described by David Stafford
128 <     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html).
129 <     * The value of GAMMA_GAMMA is arbitrary (except must be at least
130 <     * 13 and less than GAMMA_PRIME), but because it serves as the
131 <     * base of split sequences, should be subject to validation of
132 <     * consequent random number quality metrics.
118 >     * bits of 'h' to within 0.25% bias." The mix32 function is
119 >     * equivalent to (int)(mix64(seed) >>> 32), but faster because it
120 >     * omits a step that doesn't contribute to result.
121 >     *
122 >     * The split operation uses the current generator to form the seed
123 >     * and gamma for another SplittableRandom.  To conservatively
124 >     * avoid potential correlations between seed and value generation,
125 >     * gamma selection (method nextGamma) uses the "Mix13" constants
126 >     * for MurmurHash3 described by David Stafford
127 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
128 >     * To avoid potential weaknesses in bit-mixing transformations, we
129 >     * restrict gammas to odd values with at least 12 and no more than
130 >     * 52 bits set.  Rather than rejecting candidates with too few or
131 >     * too many bits set, method nextGamma flips some bits (which has
132 >     * the effect of mapping at most 4 to any given gamma value).
133 >     * This reduces the effective set of 64bit odd gamma values by
134 >     * about 2<sup>14</sup>, a very tiny percentage, and serves as an
135 >     * automated screening for sequence constant selection that is
136 >     * left as an empirical decision in some other hashing and crypto
137 >     * algorithms.
138 >     *
139 >     * The resulting generator thus transforms a sequence in which
140 >     * (typically) many bits change on each step, with an inexpensive
141 >     * mixer with good (but less than cryptographically secure)
142 >     * avalanching.
143 >     *
144 >     * The default (no-argument) constructor, in essence, invokes
145 >     * split() for a common "seeder" SplittableRandom.  Unlike other
146 >     * cases, this split must be performed in a thread-safe manner, so
147 >     * we use an AtomicLong to represent the seed rather than use an
148 >     * explicit SplittableRandom. To bootstrap the seeder, we start
149 >     * off using a seed based on current time and host unless the
150 >     * SecureRandomSeed property is set. This serves as a
151 >     * slimmed-down (and insecure) variant of SecureRandom that also
152 >     * avoids stalls that may occur when using /dev/random.
153 >     *
154 >     * It is a relatively simple matter to apply the basic design here
155 >     * to use 128 bit seeds. However, emulating 128bit arithmetic and
156 >     * carrying around twice the state add more overhead than appears
157 >     * warranted for current usages.
158       *
159 <     * The mix32 function used for nextInt just consists of two of the
160 <     * five lines of mix64; avalanche testing shows that the 64-bit
161 <     * result has its top 32 bits avalanched well, though not the
143 <     * bottom 32 bits.  DieHarder tests show that it is adequate for
144 <     * generating one random int from the 64-bit result of nextSeed.
145 <     *
146 <     * Support for the default (no-argument) constructor relies on an
147 <     * AtomicLong (defaultSeedGenerator) to help perform the
148 <     * equivalent of a split of a statically constructed
149 <     * SplittableRandom. Unlike other cases, this split must be
150 <     * performed in a thread-safe manner. We use
151 <     * AtomicLong.compareAndSet as the (typically) most efficient
152 <     * mechanism. To bootstrap, we start off using a SecureRandom
153 <     * initial default seed, and update using a fixed
154 <     * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
155 <     * not 0, for its splitSeed argument (addGammaModGeorge(0,
156 <     * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
157 <     * this root generator, even though the root is not explicitly
158 <     * represented as a SplittableRandom.
159 <     */
160 <
161 <    /**
162 <     * The prime modulus for gamma values.
163 <     */
164 <    private static final long GAMMA_PRIME = (1L << 57) - 13L;
165 <
166 <    /**
167 <     * The value for producing new gamma values. Must be greater or
168 <     * equal to 13 and less than GAMMA_PRIME. Otherwise, the value is
169 <     * arbitrary subject to validation of the resulting statistical
170 <     * quality of splits.
171 <     */
172 <    private static final long GAMMA_GAMMA = 0x00aae38294f712aabL;
173 <
174 <    /**
175 <     * The seed update value for default constructors.  Must be
176 <     * greater or equal to 13. Otherwise, the value is arbitrary
177 <     * subject to quality checks.
159 >     * File organization: First the non-public methods that constitute
160 >     * the main algorithm, then the main public methods, followed by
161 >     * some custom spliterator classes needed for stream methods.
162       */
179    private static final long DEFAULT_SEED_GAMMA = 0x9e3779b97f4a7c15L;
163  
164      /**
165 <     * The value 13 with 64bit sign bit set. Used in the signed
166 <     * comparison in addGammaModGeorge.
165 >     * The initial gamma value for (unsplit) SplittableRandoms. Must
166 >     * be odd with at least 12 and no more than 52 bits set. Currently
167 >     * set to the golden ratio scaled to 64bits.
168       */
169 <    private static final long BOTTOM13 = 0x800000000000000DL;
169 >    private static final long INITIAL_GAMMA = 0x9e3779b97f4a7c15L;
170  
171      /**
172       * The least non-zero value returned by nextDouble(). This value
# Line 191 | Line 175 | public class SplittableRandom {
175      private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
176  
177      /**
178 <     * The next seed for default constructors.
195 <     */
196 <    private static final AtomicLong defaultSeedGenerator =
197 <        new AtomicLong(getInitialDefaultSeed());
198 <
199 <    /**
200 <     * The seed, updated only via method nextSeed.
178 >     * The seed. Updated only via method nextSeed.
179       */
180      private long seed;
181  
182      /**
183 <     * The constant value added to seed (mod George) on each update.
183 >     * The step value.
184       */
185      private final long gamma;
186  
187      /**
188 <     * The next seed to use for splits. Propagated using
211 <     * addGammaModGeorge across instances.
212 <     */
213 <    private final long nextSplit;
214 <
215 <    /**
216 <     * Adds the given gamma value, g, to the given seed value s, mod
217 <     * George (2^64+13). We regard s and g as unsigned values
218 <     * (ranging from 0 to 2^64-1). We add g to s either once or twice
219 <     * (mod George) as necessary to produce an (unsigned) result less
220 <     * than 2^64.  We require that g must be at least 13. This
221 <     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
222 <     * George < 2^64; thus we need only a conditional, not a loop,
223 <     * to be sure of getting a representable value.
224 <     *
225 <     * Because Java comparison operators are signed, we implement this
226 <     * by conceptually offsetting seed values downwards by 2^63, so
227 <     * 0..13 is represented as Long.MIN_VALUE..BOTTOM13.
228 <     *
229 <     * @param s a seed value, viewed as a signed long
230 <     * @param g a gamma value, 13 <= g (as unsigned)
188 >     * Internal constructor used by all others except default constructor.
189       */
190 <    private static long addGammaModGeorge(long s, long g) {
191 <        long p = s + g;
192 <        return (p >= s) ? p : ((p >= BOTTOM13) ? p  : p + g) - 13L;
190 >    private SplittableRandom(long seed, long gamma) {
191 >        this.seed = seed;
192 >        this.gamma = gamma;
193      }
194  
195      /**
196 <     * Returns a bit-mixed transformation of its argument.
239 <     * See above for explanation.
196 >     * Computes MurmurHash3 64bit mix function.
197       */
198      private static long mix64(long z) {
199 <        z ^= (z >>> 33);
200 <        z *= 0xff51afd7ed558ccdL;
201 <        z ^= (z >>> 33);
245 <        z *= 0xc4ceb9fe1a85ec53L;
246 <        z ^= (z >>> 33);
247 <        return z;
199 >        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
200 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
201 >        return z ^ (z >>> 33);
202      }
203  
204      /**
205 <     * Returns a bit-mixed int transformation of its argument.
252 <     * See above for explanation.
205 >     * Returns the 32 high bits of mix64(z) as int.
206       */
207      private static int mix32(long z) {
208 <        z ^= (z >>> 33);
209 <        z *= 0xc4ceb9fe1a85ec53L;
257 <        return (int)(z >>> 32);
258 <    }
259 <
260 <    /**
261 <     * Returns a 57-bit mixed transformation of its argument.  See
262 <     * above for explanation.
263 <     */
264 <    private static long mix57(long z) {
265 <        z ^= (z >>> 33);
266 <        z *= 0x7fb5d329728ea185L;
267 <        z &= 0x01FFFFFFFFFFFFFFL;
268 <        z ^= (z >>> 33);
269 <        z *= 0x81dadef4bc2dd44dL;
270 <        z &= 0x01FFFFFFFFFFFFFFL;
271 <        z ^= (z >>> 33);
272 <        return z;
208 >        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
209 >        return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
210      }
211  
212      /**
213 <     * Internal constructor used by all other constructors and by
277 <     * method split. Establishes the initial seed for this instance,
278 <     * and uses the given splitSeed to establish gamma, as well as the
279 <     * nextSplit to use by this instance. The loop to skip ineligible
280 <     * gammas very rarely iterates, and does so at most 13 times.
213 >     * Returns the gamma value to use for a new split instance.
214       */
215 <    private SplittableRandom(long seed, long splitSeed) {
216 <        this.seed = seed;
217 <        long s = splitSeed, g;
218 <        do { // ensure gamma >= 13, considered as an unsigned integer
219 <            s += GAMMA_GAMMA;
220 <            if (s >= GAMMA_PRIME)
288 <                s -= GAMMA_PRIME;
289 <            g = mix57(s);
290 <        } while (g < 13L);
291 <        this.gamma = g;
292 <        this.nextSplit = s;
215 >    private static long nextGamma(long z) {
216 >        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; // Stafford "Mix13"
217 >        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
218 >        z = (z ^ (z >>> 31)) | 1L; // force to be odd
219 >        int n = Long.bitCount(z);  // ensure enough 0 and 1 bits
220 >        return (n < 12 || n > 52) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
221      }
222  
223      /**
224 <     * Updates in-place and returns seed.
297 <     * See above for explanation.
224 >     * Adds gamma to seed.
225       */
226      private long nextSeed() {
227 <        return seed = addGammaModGeorge(seed, gamma);
227 >        return seed += gamma;
228      }
229  
230      /**
231 <     * Atomically updates and returns next seed for default constructor.
231 >     * The seed generator for default constructors.
232       */
233 <    private static long nextDefaultSeed() {
307 <        long oldSeed, newSeed;
308 <        do {
309 <            oldSeed = defaultSeedGenerator.get();
310 <            newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
311 <        } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
312 <        return mix64(newSeed);
313 <    }
233 >    private static final AtomicLong seeder = new AtomicLong(initialSeed());
234  
235 <    /**
236 <     * Returns an initial default seed.
237 <     */
238 <    private static long getInitialDefaultSeed() {
239 <        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
240 <        long s = (long)(seedBytes[0]) & 0xffL;
241 <        for (int i = 1; i < 8; ++i)
242 <            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
243 <        return s;
235 >    private static long initialSeed() {
236 >        try {  // ignore exceptions in accessing/parsing properties
237 >            String pp = System.getProperty
238 >                ("java.util.secureRandomSeed");
239 >            if (pp != null && pp.equalsIgnoreCase("true")) {
240 >                byte[] seedBytes = java.security.SecureRandom.getSeed(8);
241 >                long s = (long)(seedBytes[0]) & 0xffL;
242 >                for (int i = 1; i < 8; ++i)
243 >                    s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
244 >                return s;
245 >            }
246 >        } catch (Exception ignore) {
247 >        }
248 >        int hh = 0; // hashed host address
249 >        try {
250 >            hh = InetAddress.getLocalHost().hashCode();
251 >        } catch (Exception ignore) {
252 >        }
253 >        return (mix64((((long)hh) << 32) ^ System.currentTimeMillis()) ^
254 >                mix64(System.nanoTime()));
255      }
256  
257 +    // IllegalArgumentException messages
258 +    static final String BadBound = "bound must be positive";
259 +    static final String BadRange = "bound must be greater than origin";
260 +    static final String BadSize  = "size must be non-negative";
261 +
262      /*
263       * Internal versions of nextX methods used by streams, as well as
264       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 442 | Line 378 | public class SplittableRandom {
378       * @param seed the initial seed
379       */
380      public SplittableRandom(long seed) {
381 <        this(seed, 0L);
381 >        this(seed, INITIAL_GAMMA);
382      }
383  
384      /**
# Line 451 | Line 387 | public class SplittableRandom {
387       * of those of any other instances in the current program; and
388       * may, and typically does, vary across program invocations.
389       */
390 <    public SplittableRandom() {
391 <        this(nextDefaultSeed(), GAMMA_GAMMA);
390 >    public SplittableRandom() { // emulate seeder.split()
391 >        this.gamma = nextGamma(this.seed = seeder.addAndGet(INITIAL_GAMMA));
392      }
393  
394      /**
# Line 470 | Line 406 | public class SplittableRandom {
406       * @return the new SplittableRandom instance
407       */
408      public SplittableRandom split() {
409 <        return new SplittableRandom(nextSeed(), nextSplit);
409 >        long s = nextSeed();
410 >        return new SplittableRandom(s, nextGamma(s));
411      }
412  
413      /**
# Line 486 | Line 423 | public class SplittableRandom {
423       * Returns a pseudorandom {@code int} value between zero (inclusive)
424       * and the specified bound (exclusive).
425       *
426 <     * @param bound the bound on the random number to be returned.  Must be
490 <     *        positive.
426 >     * @param bound the upper bound (exclusive).  Must be positive.
427       * @return a pseudorandom {@code int} value between zero
428       *         (inclusive) and the bound (exclusive)
429 <     * @throws IllegalArgumentException if the bound is less than zero
429 >     * @throws IllegalArgumentException if {@code bound} is not positive
430       */
431      public int nextInt(int bound) {
432          if (bound <= 0)
433 <            throw new IllegalArgumentException("bound must be positive");
433 >            throw new IllegalArgumentException(BadBound);
434          // Specialize internalNextInt for origin 0
435          int r = mix32(nextSeed());
436          int m = bound - 1;
# Line 522 | Line 458 | public class SplittableRandom {
458       */
459      public int nextInt(int origin, int bound) {
460          if (origin >= bound)
461 <            throw new IllegalArgumentException("bound must be greater than origin");
461 >            throw new IllegalArgumentException(BadRange);
462          return internalNextInt(origin, bound);
463      }
464  
# Line 539 | Line 475 | public class SplittableRandom {
475       * Returns a pseudorandom {@code long} value between zero (inclusive)
476       * and the specified bound (exclusive).
477       *
478 <     * @param bound the bound on the random number to be returned.  Must be
543 <     *        positive.
478 >     * @param bound the upper bound (exclusive).  Must be positive.
479       * @return a pseudorandom {@code long} value between zero
480       *         (inclusive) and the bound (exclusive)
481 <     * @throws IllegalArgumentException if {@code bound} is less than zero
481 >     * @throws IllegalArgumentException if {@code bound} is not positive
482       */
483      public long nextLong(long bound) {
484          if (bound <= 0)
485 <            throw new IllegalArgumentException("bound must be positive");
485 >            throw new IllegalArgumentException(BadBound);
486          // Specialize internalNextLong for origin 0
487          long r = mix64(nextSeed());
488          long m = bound - 1;
# Line 575 | Line 510 | public class SplittableRandom {
510       */
511      public long nextLong(long origin, long bound) {
512          if (origin >= bound)
513 <            throw new IllegalArgumentException("bound must be greater than origin");
513 >            throw new IllegalArgumentException(BadRange);
514          return internalNextLong(origin, bound);
515      }
516  
# Line 584 | Line 519 | public class SplittableRandom {
519       * (inclusive) and one (exclusive).
520       *
521       * @return a pseudorandom {@code double} value between zero
522 <     * (inclusive) and one (exclusive)
522 >     *         (inclusive) and one (exclusive)
523       */
524      public double nextDouble() {
525          return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
# Line 594 | Line 529 | public class SplittableRandom {
529       * Returns a pseudorandom {@code double} value between 0.0
530       * (inclusive) and the specified bound (exclusive).
531       *
532 <     * @param bound the bound on the random number to be returned.  Must be
598 <     *        positive.
532 >     * @param bound the upper bound (exclusive).  Must be positive.
533       * @return a pseudorandom {@code double} value between zero
534       *         (inclusive) and the bound (exclusive)
535 <     * @throws IllegalArgumentException if {@code bound} is less than zero
535 >     * @throws IllegalArgumentException if {@code bound} is not positive
536       */
537      public double nextDouble(double bound) {
538          if (!(bound > 0.0))
539 <            throw new IllegalArgumentException("bound must be positive");
539 >            throw new IllegalArgumentException(BadBound);
540          double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
541          return (result < bound) ?  result : // correct for rounding
542              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
# Line 613 | Line 547 | public class SplittableRandom {
547       * origin (inclusive) and bound (exclusive).
548       *
549       * @param origin the least value returned
550 <     * @param bound the upper bound
550 >     * @param bound the upper bound (exclusive)
551       * @return a pseudorandom {@code double} value between the origin
552       *         (inclusive) and the bound (exclusive)
553       * @throws IllegalArgumentException if {@code origin} is greater than
# Line 621 | Line 555 | public class SplittableRandom {
555       */
556      public double nextDouble(double origin, double bound) {
557          if (!(origin < bound))
558 <            throw new IllegalArgumentException("bound must be greater than origin");
558 >            throw new IllegalArgumentException(BadRange);
559          return internalNextDouble(origin, bound);
560      }
561  
# Line 638 | Line 572 | public class SplittableRandom {
572      // maintenance purposes the small differences across forms.
573  
574      /**
575 <     * Returns a stream producing the given {@code streamSize} number of
576 <     * pseudorandom {@code int} values.
575 >     * Returns a stream producing the given {@code streamSize} number
576 >     * of pseudorandom {@code int} values from this generator and/or
577 >     * one split from it.
578       *
579       * @param streamSize the number of values to generate
580       * @return a stream of pseudorandom {@code int} values
# Line 648 | Line 583 | public class SplittableRandom {
583       */
584      public IntStream ints(long streamSize) {
585          if (streamSize < 0L)
586 <            throw new IllegalArgumentException("negative Stream size");
586 >            throw new IllegalArgumentException(BadSize);
587          return StreamSupport.intStream
588              (new RandomIntsSpliterator
589               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 657 | Line 592 | public class SplittableRandom {
592  
593      /**
594       * Returns an effectively unlimited stream of pseudorandom {@code int}
595 <     * values.
595 >     * values from this generator and/or one split from it.
596       *
597       * @implNote This method is implemented to be equivalent to {@code
598       * ints(Long.MAX_VALUE)}.
# Line 672 | Line 607 | public class SplittableRandom {
607      }
608  
609      /**
610 <     * Returns a stream producing the given {@code streamSize} number of
611 <     * pseudorandom {@code int} values, each conforming to the given
612 <     * origin and bound.
610 >     * Returns a stream producing the given {@code streamSize} number
611 >     * of pseudorandom {@code int} values from this generator and/or one split
612 >     * from it; each value conforms to the given origin (inclusive) and bound
613 >     * (exclusive).
614       *
615       * @param streamSize the number of values to generate
616 <     * @param randomNumberOrigin the origin of each random value
617 <     * @param randomNumberBound the bound of each random value
616 >     * @param randomNumberOrigin the origin (inclusive) of each random value
617 >     * @param randomNumberBound the bound (exclusive) of each random value
618       * @return a stream of pseudorandom {@code int} values,
619 <     *         each with the given origin and bound
619 >     *         each with the given origin (inclusive) and bound (exclusive)
620       * @throws IllegalArgumentException if {@code streamSize} is
621       *         less than zero, or {@code randomNumberOrigin}
622       *         is greater than or equal to {@code randomNumberBound}
# Line 688 | Line 624 | public class SplittableRandom {
624      public IntStream ints(long streamSize, int randomNumberOrigin,
625                            int randomNumberBound) {
626          if (streamSize < 0L)
627 <            throw new IllegalArgumentException("negative Stream size");
627 >            throw new IllegalArgumentException(BadSize);
628          if (randomNumberOrigin >= randomNumberBound)
629 <            throw new IllegalArgumentException("bound must be greater than origin");
629 >            throw new IllegalArgumentException(BadRange);
630          return StreamSupport.intStream
631              (new RandomIntsSpliterator
632               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 699 | Line 635 | public class SplittableRandom {
635  
636      /**
637       * Returns an effectively unlimited stream of pseudorandom {@code
638 <     * int} values, each conforming to the given origin and bound.
638 >     * int} values from this generator and/or one split from it; each value
639 >     * conforms to the given origin (inclusive) and bound (exclusive).
640       *
641       * @implNote This method is implemented to be equivalent to {@code
642       * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
643       *
644 <     * @param randomNumberOrigin the origin of each random value
645 <     * @param randomNumberBound the bound of each random value
644 >     * @param randomNumberOrigin the origin (inclusive) of each random value
645 >     * @param randomNumberBound the bound (exclusive) of each random value
646       * @return a stream of pseudorandom {@code int} values,
647 <     *         each with the given origin and bound
647 >     *         each with the given origin (inclusive) and bound (exclusive)
648       * @throws IllegalArgumentException if {@code randomNumberOrigin}
649       *         is greater than or equal to {@code randomNumberBound}
650       */
651      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
652          if (randomNumberOrigin >= randomNumberBound)
653 <            throw new IllegalArgumentException("bound must be greater than origin");
653 >            throw new IllegalArgumentException(BadRange);
654          return StreamSupport.intStream
655              (new RandomIntsSpliterator
656               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 721 | Line 658 | public class SplittableRandom {
658      }
659  
660      /**
661 <     * Returns a stream producing the given {@code streamSize} number of
662 <     * pseudorandom {@code long} values.
661 >     * Returns a stream producing the given {@code streamSize} number
662 >     * of pseudorandom {@code long} values from this generator and/or
663 >     * one split from it.
664       *
665       * @param streamSize the number of values to generate
666       * @return a stream of pseudorandom {@code long} values
# Line 731 | Line 669 | public class SplittableRandom {
669       */
670      public LongStream longs(long streamSize) {
671          if (streamSize < 0L)
672 <            throw new IllegalArgumentException("negative Stream size");
672 >            throw new IllegalArgumentException(BadSize);
673          return StreamSupport.longStream
674              (new RandomLongsSpliterator
675               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 739 | Line 677 | public class SplittableRandom {
677      }
678  
679      /**
680 <     * Returns an effectively unlimited stream of pseudorandom {@code long}
681 <     * values.
680 >     * Returns an effectively unlimited stream of pseudorandom {@code
681 >     * long} values from this generator and/or one split from it.
682       *
683       * @implNote This method is implemented to be equivalent to {@code
684       * longs(Long.MAX_VALUE)}.
# Line 756 | Line 694 | public class SplittableRandom {
694  
695      /**
696       * Returns a stream producing the given {@code streamSize} number of
697 <     * pseudorandom {@code long} values, each conforming to the
698 <     * given origin and bound.
697 >     * pseudorandom {@code long} values from this generator and/or one split
698 >     * from it; each value conforms to the given origin (inclusive) and bound
699 >     * (exclusive).
700       *
701       * @param streamSize the number of values to generate
702 <     * @param randomNumberOrigin the origin of each random value
703 <     * @param randomNumberBound the bound of each random value
702 >     * @param randomNumberOrigin the origin (inclusive) of each random value
703 >     * @param randomNumberBound the bound (exclusive) of each random value
704       * @return a stream of pseudorandom {@code long} values,
705 <     *         each with the given origin and bound
705 >     *         each with the given origin (inclusive) and bound (exclusive)
706       * @throws IllegalArgumentException if {@code streamSize} is
707       *         less than zero, or {@code randomNumberOrigin}
708       *         is greater than or equal to {@code randomNumberBound}
# Line 771 | Line 710 | public class SplittableRandom {
710      public LongStream longs(long streamSize, long randomNumberOrigin,
711                              long randomNumberBound) {
712          if (streamSize < 0L)
713 <            throw new IllegalArgumentException("negative Stream size");
713 >            throw new IllegalArgumentException(BadSize);
714          if (randomNumberOrigin >= randomNumberBound)
715 <            throw new IllegalArgumentException("bound must be greater than origin");
715 >            throw new IllegalArgumentException(BadRange);
716          return StreamSupport.longStream
717              (new RandomLongsSpliterator
718               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 782 | Line 721 | public class SplittableRandom {
721  
722      /**
723       * Returns an effectively unlimited stream of pseudorandom {@code
724 <     * long} values, each conforming to the given origin and bound.
724 >     * long} values from this generator and/or one split from it; each value
725 >     * conforms to the given origin (inclusive) and bound (exclusive).
726       *
727       * @implNote This method is implemented to be equivalent to {@code
728       * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
729       *
730 <     * @param randomNumberOrigin the origin of each random value
731 <     * @param randomNumberBound the bound of each random value
730 >     * @param randomNumberOrigin the origin (inclusive) of each random value
731 >     * @param randomNumberBound the bound (exclusive) of each random value
732       * @return a stream of pseudorandom {@code long} values,
733 <     *         each with the given origin and bound
733 >     *         each with the given origin (inclusive) and bound (exclusive)
734       * @throws IllegalArgumentException if {@code randomNumberOrigin}
735       *         is greater than or equal to {@code randomNumberBound}
736       */
737      public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
738          if (randomNumberOrigin >= randomNumberBound)
739 <            throw new IllegalArgumentException("bound must be greater than origin");
739 >            throw new IllegalArgumentException(BadRange);
740          return StreamSupport.longStream
741              (new RandomLongsSpliterator
742               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 805 | Line 745 | public class SplittableRandom {
745  
746      /**
747       * Returns a stream producing the given {@code streamSize} number of
748 <     * pseudorandom {@code double} values, each between zero
749 <     * (inclusive) and one (exclusive).
748 >     * pseudorandom {@code double} values from this generator and/or one split
749 >     * from it; each value is between zero (inclusive) and one (exclusive).
750       *
751       * @param streamSize the number of values to generate
752       * @return a stream of {@code double} values
# Line 815 | Line 755 | public class SplittableRandom {
755       */
756      public DoubleStream doubles(long streamSize) {
757          if (streamSize < 0L)
758 <            throw new IllegalArgumentException("negative Stream size");
758 >            throw new IllegalArgumentException(BadSize);
759          return StreamSupport.doubleStream
760              (new RandomDoublesSpliterator
761               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 824 | Line 764 | public class SplittableRandom {
764  
765      /**
766       * Returns an effectively unlimited stream of pseudorandom {@code
767 <     * double} values, each between zero (inclusive) and one
768 <     * (exclusive).
767 >     * double} values from this generator and/or one split from it; each value
768 >     * is between zero (inclusive) and one (exclusive).
769       *
770       * @implNote This method is implemented to be equivalent to {@code
771       * doubles(Long.MAX_VALUE)}.
# Line 841 | Line 781 | public class SplittableRandom {
781  
782      /**
783       * Returns a stream producing the given {@code streamSize} number of
784 <     * pseudorandom {@code double} values, each conforming to the
785 <     * given origin and bound.
784 >     * pseudorandom {@code double} values from this generator and/or one split
785 >     * from it; each value conforms to the given origin (inclusive) and bound
786 >     * (exclusive).
787       *
788       * @param streamSize the number of values to generate
789 <     * @param randomNumberOrigin the origin of each random value
790 <     * @param randomNumberBound the bound of each random value
789 >     * @param randomNumberOrigin the origin (inclusive) of each random value
790 >     * @param randomNumberBound the bound (exclusive) of each random value
791       * @return a stream of pseudorandom {@code double} values,
792 <     * each with the given origin and bound
792 >     *         each with the given origin (inclusive) and bound (exclusive)
793       * @throws IllegalArgumentException if {@code streamSize} is
794 <     * less than zero
794 >     *         less than zero
795       * @throws IllegalArgumentException if {@code randomNumberOrigin}
796       *         is greater than or equal to {@code randomNumberBound}
797       */
798      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
799                                  double randomNumberBound) {
800          if (streamSize < 0L)
801 <            throw new IllegalArgumentException("negative Stream size");
801 >            throw new IllegalArgumentException(BadSize);
802          if (!(randomNumberOrigin < randomNumberBound))
803 <            throw new IllegalArgumentException("bound must be greater than origin");
803 >            throw new IllegalArgumentException(BadRange);
804          return StreamSupport.doubleStream
805              (new RandomDoublesSpliterator
806               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 868 | Line 809 | public class SplittableRandom {
809  
810      /**
811       * Returns an effectively unlimited stream of pseudorandom {@code
812 <     * double} values, each conforming to the given origin and bound.
812 >     * double} values from this generator and/or one split from it; each value
813 >     * conforms to the given origin (inclusive) and bound (exclusive).
814       *
815       * @implNote This method is implemented to be equivalent to {@code
816       * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
817       *
818 <     * @param randomNumberOrigin the origin of each random value
819 <     * @param randomNumberBound the bound of each random value
818 >     * @param randomNumberOrigin the origin (inclusive) of each random value
819 >     * @param randomNumberBound the bound (exclusive) of each random value
820       * @return a stream of pseudorandom {@code double} values,
821 <     * each with the given origin and bound
821 >     *         each with the given origin (inclusive) and bound (exclusive)
822       * @throws IllegalArgumentException if {@code randomNumberOrigin}
823       *         is greater than or equal to {@code randomNumberBound}
824       */
825      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
826          if (!(randomNumberOrigin < randomNumberBound))
827 <            throw new IllegalArgumentException("bound must be greater than origin");
827 >            throw new IllegalArgumentException(BadRange);
828          return StreamSupport.doubleStream
829              (new RandomDoublesSpliterator
830               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 940 | Line 882 | public class SplittableRandom {
882              long i = index, f = fence;
883              if (i < f) {
884                  index = f;
885 +                SplittableRandom r = rng;
886                  int o = origin, b = bound;
887                  do {
888 <                    consumer.accept(rng.internalNextInt(o, b));
888 >                    consumer.accept(r.internalNextInt(o, b));
889                  } while (++i < f);
890              }
891          }
# Line 994 | Line 937 | public class SplittableRandom {
937              long i = index, f = fence;
938              if (i < f) {
939                  index = f;
940 +                SplittableRandom r = rng;
941                  long o = origin, b = bound;
942                  do {
943 <                    consumer.accept(rng.internalNextLong(o, b));
943 >                    consumer.accept(r.internalNextLong(o, b));
944                  } while (++i < f);
945              }
946          }
# Line 1049 | Line 993 | public class SplittableRandom {
993              long i = index, f = fence;
994              if (i < f) {
995                  index = f;
996 +                SplittableRandom r = rng;
997                  double o = origin, b = bound;
998                  do {
999 <                    consumer.accept(rng.internalNextDouble(o, b));
999 >                    consumer.accept(r.internalNextDouble(o, b));
1000                  } while (++i < f);
1001              }
1002          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines