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.12 by dl, Sun Jul 21 14:02:23 2013 UTC vs.
Revision 1.22 by dl, Fri Sep 20 09:38:07 2013 UTC

# Line 26 | Line 26
26   package java.util;
27  
28   import java.security.SecureRandom;
29 + import java.net.NetworkInterface;
30 + import java.util.Enumeration;
31   import java.util.concurrent.atomic.AtomicLong;
30 import java.util.Spliterator;
32   import java.util.function.IntConsumer;
33   import java.util.function.LongConsumer;
34   import java.util.function.DoubleConsumer;
# Line 39 | Line 40 | import java.util.stream.DoubleStream;
40   /**
41   * A generator of uniform pseudorandom values applicable for use in
42   * (among other contexts) isolated parallel computations that may
43 < * generate subtasks. Class SplittableRandom supports methods for
43 > * generate subtasks. Class {@code SplittableRandom} supports methods for
44   * producing pseudorandom numbers of type {@code int}, {@code long},
45   * and {@code double} with similar usages as for class
46   * {@link java.util.Random} but differs in the following ways:
# Line 77 | Line 78 | import java.util.stream.DoubleStream;
78   *
79   * </ul>
80   *
81 + * <p>Instances of {@code SplittableRandom} are not cryptographically
82 + * secure.  Consider instead using {@link java.security.SecureRandom}
83 + * in security-sensitive applications. Additionally,
84 + * default-constructed instances do not use a cryptographically random
85 + * seed unless the {@linkplain System#getProperty system property}
86 + * {@code java.util.secureRandomSeed} is set to {@code true}.
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.
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 function is based on David Stafford's
113 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
114 >     * "Mix13" variant of the "64-bit finalizer" function in Austin
115 >     * Appleby's MurmurHash3 algorithm See
116 >     * http://code.google.com/p/smhasher/wiki/MurmurHash3 . The mix32
117 >     * function is based on Stafford's Mix04 mix function, but returns
118 >     * the upper 32 bits cast as int.
119 >     *
120 >     * The split operation uses the current generator to form the seed
121 >     * and gamma for another SplittableRandom.  To conservatively
122 >     * avoid potential correlations between seed and value generation,
123 >     * gamma selection (method mixGamma) uses different
124 >     * (Murmurhash3's) mix constants.  To avoid potential weaknesses
125 >     * in bit-mixing transformations, we restrict gammas to odd values
126 >     * with at least 24 0-1 or 1-0 bit transitions.  Rather than
127 >     * rejecting candidates with too few or too many bits set, method
128 >     * mixGamma flips some bits (which has the effect of mapping at
129 >     * most 4 to any given gamma value).  This reduces the effective
130 >     * set of 64bit odd gamma values by about 2%, and serves as an
131 >     * automated screening for sequence constant selection that is
132 >     * left as an empirical decision in some other hashing and crypto
133 >     * algorithms.
134 >     *
135 >     * The resulting generator thus transforms a sequence in which
136 >     * (typically) many bits change on each step, with an inexpensive
137 >     * mixer with good (but less than cryptographically secure)
138 >     * avalanching.
139 >     *
140 >     * The default (no-argument) constructor, in essence, invokes
141 >     * split() for a common "defaultGen" SplittableRandom.  Unlike
142 >     * other cases, this split must be performed in a thread-safe
143 >     * manner, so we use an AtomicLong to represent the seed rather
144 >     * than use an explicit SplittableRandom. To bootstrap the
145 >     * defaultGen, we start off using a seed based on current time and
146 >     * network interface address unless the java.util.secureRandomSeed
147 >     * property is set. This serves as a slimmed-down (and insecure)
148 >     * variant of SecureRandom that also avoids stalls that may occur
149 >     * when using /dev/random.
150 >     *
151 >     * It is a relatively simple matter to apply the basic design here
152 >     * to use 128 bit seeds. However, emulating 128bit arithmetic and
153 >     * carrying around twice the state add more overhead than appears
154 >     * warranted for current usages.
155       *
156 <     * The primary update step (see method nextSeed()) is simply to
157 <     * add a constant ("gamma") to the current seed, modulo a prime
158 <     * ("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 <     *
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 <     * not calls to nextSeed(): Each instance carries the state of
122 <     * 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 <     * 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 <     *
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 <     * 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 <     */
162 <
163 <    /**
164 <     * 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 <     */
168 <    private static final long GAMMA_GAMMA = 0xF2281E2DBA6606F3L;
169 <
170 <    /**
171 <     * The seed update value for default constructors.  Must be
172 <     * greater or equal to 13. Otherwise, the value is arbitrary.
156 >     * File organization: First the non-public methods that constitute
157 >     * the main algorithm, then the main public methods, followed by
158 >     * some custom spliterator classes needed for stream methods.
159       */
174    private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
160  
161      /**
162 <     * The value 13 with 64bit sign bit set. Used in the signed
163 <     * comparison in addGammaModGeorge.
162 >     * The golden ratio scaled to 64bits, used as the initial gamma
163 >     * value for (unsplit) SplittableRandoms.
164       */
165 <    private static final long BOTTOM13 = 0x800000000000000DL;
165 >    private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
166  
167      /**
168       * The least non-zero value returned by nextDouble(). This value
169       * is scaled by a random value of 53 bits to produce a result.
170       */
171 <    private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
171 >    private static final double DOUBLE_ULP = 1.0 / (1L << 53);
172  
173      /**
174 <     * The next seed for default constructors.
190 <     */
191 <    private static final AtomicLong defaultSeedGenerator =
192 <        new AtomicLong(getInitialDefaultSeed());
193 <
194 <    /**
195 <     * The seed, updated only via method nextSeed.
174 >     * The seed. Updated only via method nextSeed.
175       */
176      private long seed;
177  
178      /**
179 <     * The constant value added to seed (mod George) on each update.
179 >     * The step value.
180       */
181      private final long gamma;
182  
183      /**
184 <     * 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 <     * 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 <     * @param g a gamma value, 13 <= g (as unsigned)
184 >     * Internal constructor used by all others except default constructor.
185       */
186 <    private static long addGammaModGeorge(long s, long g) {
187 <        long p = s + g;
188 <        return (p >= s) ? p : ((p >= BOTTOM13) ? p  : p + g) - 13L;
186 >    private SplittableRandom(long seed, long gamma) {
187 >        this.seed = seed;
188 >        this.gamma = gamma;
189      }
190  
191      /**
192 <     * Returns a bit-mixed transformation of its argument.
234 <     * See above for explanation.
192 >     * Computes Stafford variant 13 of 64bit mix function.
193       */
194      private static long mix64(long z) {
195 <        z ^= (z >>> 33);
196 <        z *= 0xff51afd7ed558ccdL;
197 <        z ^= (z >>> 33);
240 <        z *= 0xc4ceb9fe1a85ec53L;
241 <        z ^= (z >>> 33);
242 <        return z;
195 >        z *= 0xbf58476d1ce4e5b9L;
196 >        z = (z ^ (z >>> 32)) * 0x94d049bb133111ebL;
197 >        return z ^ (z >>> 32);
198      }
199  
200      /**
201 <     * Returns a bit-mixed int transformation of its argument.
247 <     * See above for explanation.
201 >     * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
202       */
203      private static int mix32(long z) {
204 <        z ^= (z >>> 33);
205 <        z *= 0xc4ceb9fe1a85ec53L;
252 <        return (int)(z >>> 32);
204 >        z *= 0x62a9d9ed799705f5L;
205 >        return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
206      }
207  
208      /**
209 <     * 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.
209 >     * Returns the gamma value to use for a new split instance.
210       */
211 <    private SplittableRandom(long seed, long splitSeed) {
212 <        this.seed = seed;
213 <        long s = splitSeed, g;
214 <        do { // ensure gamma >= 13, considered as an unsigned integer
215 <            s = addGammaModGeorge(s, GAMMA_GAMMA);
216 <            g = mix64(s);
268 <        } while (g >= 0L && g < 13L);
269 <        this.gamma = g;
270 <        this.nextSplit = s;
211 >    private static long mixGamma(long z) {
212 >        z *= 0xff51afd7ed558ccdL;                   // MurmurHash3 mix constants
213 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
214 >        z = (z ^ (z >>> 33)) | 1L;                  // force to be odd
215 >        int n = Long.bitCount(z ^ (z >>> 1));       // ensure enough transitions
216 >        return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
217      }
218  
219      /**
220 <     * Updates in-place and returns seed.
275 <     * See above for explanation.
220 >     * Adds gamma to seed.
221       */
222      private long nextSeed() {
223 <        return seed = addGammaModGeorge(seed, gamma);
223 >        return seed += gamma;
224      }
225  
226      /**
227 <     * Atomically updates and returns next seed for default constructor.
227 >     * The seed generator for default constructors.
228       */
229 <    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 <    }
229 >    private static final AtomicLong defaultGen = new AtomicLong(initialSeed());
230  
231 <    /**
232 <     * Returns an initial default seed.
233 <     */
234 <    private static long getInitialDefaultSeed() {
235 <        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
236 <        long s = (long)(seedBytes[0]) & 0xffL;
237 <        for (int i = 1; i < 8; ++i)
238 <            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
239 <        return s;
231 >    private static long initialSeed() {
232 >        String pp = java.security.AccessController.doPrivileged(
233 >                new sun.security.action.GetPropertyAction(
234 >                        "java.util.secureRandomSeed"));
235 >        if (pp != null && pp.equalsIgnoreCase("true")) {
236 >            byte[] seedBytes = java.security.SecureRandom.getSeed(8);
237 >            long s = (long)(seedBytes[0]) & 0xffL;
238 >            for (int i = 1; i < 8; ++i)
239 >                s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
240 >            return s;
241 >        }
242 >        long h = 0L;
243 >        try {
244 >            Enumeration<NetworkInterface> ifcs =
245 >                NetworkInterface.getNetworkInterfaces();
246 >            boolean retry = false; // retry once if getHardwareAddress is null
247 >            while (ifcs.hasMoreElements()) {
248 >                NetworkInterface ifc = ifcs.nextElement();
249 >                if (!ifc.isVirtual()) { // skip fake addresses
250 >                    byte[] bs = ifc.getHardwareAddress();
251 >                    if (bs != null) {
252 >                        int n = bs.length;
253 >                        int m = Math.min(n >>> 1, 4);
254 >                        for (int i = 0; i < m; ++i)
255 >                            h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
256 >                        if (m < 4)
257 >                            h = (h << 8) ^ bs[n-1-m];
258 >                        h = mix64(h);
259 >                        break;
260 >                    }
261 >                    else if (!retry)
262 >                        retry = true;
263 >                    else
264 >                        break;
265 >                }
266 >            }
267 >        } catch (Exception ignore) {
268 >        }
269 >        return (h ^ mix64(System.currentTimeMillis()) ^
270 >                mix64(System.nanoTime()));
271      }
272  
273 +    // IllegalArgumentException messages
274 +    static final String BadBound = "bound must be positive";
275 +    static final String BadRange = "bound must be greater than origin";
276 +    static final String BadSize  = "size must be non-negative";
277 +
278      /*
279       * Internal versions of nextX methods used by streams, as well as
280       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 376 | Line 350 | public class SplittableRandom {
350          int r = mix32(nextSeed());
351          if (origin < bound) {
352              int n = bound - origin, m = n - 1;
353 <            if ((n & m) == 0L)
353 >            if ((n & m) == 0)
354                  r = (r & m) + origin;
355              else if (n > 0) {
356                  for (int u = r >>> 1;
# Line 401 | Line 375 | public class SplittableRandom {
375       * @return a pseudorandom value
376       */
377      final double internalNextDouble(double origin, double bound) {
378 <        double r = (nextLong() >>> 11) * DOUBLE_UNIT;
378 >        double r = (nextLong() >>> 11) * DOUBLE_ULP;
379          if (origin < bound) {
380              r = r * (bound - origin) + origin;
381              if (r >= bound) // correct for rounding
# Line 420 | Line 394 | public class SplittableRandom {
394       * @param seed the initial seed
395       */
396      public SplittableRandom(long seed) {
397 <        this(seed, 0);
397 >        this(seed, GOLDEN_GAMMA);
398      }
399  
400      /**
# Line 429 | Line 403 | public class SplittableRandom {
403       * of those of any other instances in the current program; and
404       * may, and typically does, vary across program invocations.
405       */
406 <    public SplittableRandom() {
407 <        this(nextDefaultSeed(), GAMMA_GAMMA);
406 >    public SplittableRandom() { // emulate defaultGen.split()
407 >        long s = defaultGen.getAndAdd(2*GOLDEN_GAMMA);
408 >        this.seed = mix64(s);
409 >        this.gamma = mixGamma(s + GOLDEN_GAMMA);
410      }
411  
412      /**
# Line 448 | Line 424 | public class SplittableRandom {
424       * @return the new SplittableRandom instance
425       */
426      public SplittableRandom split() {
427 <        return new SplittableRandom(nextSeed(), nextSplit);
427 >        return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
428      }
429  
430      /**
# Line 464 | Line 440 | public class SplittableRandom {
440       * Returns a pseudorandom {@code int} value between zero (inclusive)
441       * and the specified bound (exclusive).
442       *
443 <     * @param bound the bound on the random number to be returned.  Must be
468 <     *        positive.
443 >     * @param bound the upper bound (exclusive).  Must be positive.
444       * @return a pseudorandom {@code int} value between zero
445       *         (inclusive) and the bound (exclusive)
446 <     * @throws IllegalArgumentException if the bound is less than zero
446 >     * @throws IllegalArgumentException if {@code bound} is not positive
447       */
448      public int nextInt(int bound) {
449          if (bound <= 0)
450 <            throw new IllegalArgumentException("bound must be positive");
450 >            throw new IllegalArgumentException(BadBound);
451          // Specialize internalNextInt for origin 0
452          int r = mix32(nextSeed());
453          int m = bound - 1;
454 <        if ((bound & m) == 0L) // power of two
454 >        if ((bound & m) == 0) // power of two
455              r &= m;
456          else { // reject over-represented candidates
457              for (int u = r >>> 1;
# Line 500 | Line 475 | public class SplittableRandom {
475       */
476      public int nextInt(int origin, int bound) {
477          if (origin >= bound)
478 <            throw new IllegalArgumentException("bound must be greater than origin");
478 >            throw new IllegalArgumentException(BadRange);
479          return internalNextInt(origin, bound);
480      }
481  
# Line 517 | Line 492 | public class SplittableRandom {
492       * Returns a pseudorandom {@code long} value between zero (inclusive)
493       * and the specified bound (exclusive).
494       *
495 <     * @param bound the bound on the random number to be returned.  Must be
521 <     *        positive.
495 >     * @param bound the upper bound (exclusive).  Must be positive.
496       * @return a pseudorandom {@code long} value between zero
497       *         (inclusive) and the bound (exclusive)
498 <     * @throws IllegalArgumentException if {@code bound} is less than zero
498 >     * @throws IllegalArgumentException if {@code bound} is not positive
499       */
500      public long nextLong(long bound) {
501          if (bound <= 0)
502 <            throw new IllegalArgumentException("bound must be positive");
502 >            throw new IllegalArgumentException(BadBound);
503          // Specialize internalNextLong for origin 0
504          long r = mix64(nextSeed());
505          long m = bound - 1;
# Line 553 | Line 527 | public class SplittableRandom {
527       */
528      public long nextLong(long origin, long bound) {
529          if (origin >= bound)
530 <            throw new IllegalArgumentException("bound must be greater than origin");
530 >            throw new IllegalArgumentException(BadRange);
531          return internalNextLong(origin, bound);
532      }
533  
# Line 562 | Line 536 | public class SplittableRandom {
536       * (inclusive) and one (exclusive).
537       *
538       * @return a pseudorandom {@code double} value between zero
539 <     * (inclusive) and one (exclusive)
539 >     *         (inclusive) and one (exclusive)
540       */
541      public double nextDouble() {
542 <        return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
542 >        return (mix64(nextSeed()) >>> 11) * DOUBLE_ULP;
543      }
544  
545      /**
546       * Returns a pseudorandom {@code double} value between 0.0
547       * (inclusive) and the specified bound (exclusive).
548       *
549 <     * @param bound the bound on the random number to be returned.  Must be
576 <     *        positive.
549 >     * @param bound the upper bound (exclusive).  Must be positive.
550       * @return a pseudorandom {@code double} value between zero
551       *         (inclusive) and the bound (exclusive)
552 <     * @throws IllegalArgumentException if {@code bound} is less than zero
552 >     * @throws IllegalArgumentException if {@code bound} is not positive
553       */
554      public double nextDouble(double bound) {
555          if (!(bound > 0.0))
556 <            throw new IllegalArgumentException("bound must be positive");
557 <        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
556 >            throw new IllegalArgumentException(BadBound);
557 >        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_ULP * bound;
558          return (result < bound) ?  result : // correct for rounding
559              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
560      }
# Line 591 | Line 564 | public class SplittableRandom {
564       * origin (inclusive) and bound (exclusive).
565       *
566       * @param origin the least value returned
567 <     * @param bound the upper bound
567 >     * @param bound the upper bound (exclusive)
568       * @return a pseudorandom {@code double} value between the origin
569       *         (inclusive) and the bound (exclusive)
570       * @throws IllegalArgumentException if {@code origin} is greater than
# Line 599 | Line 572 | public class SplittableRandom {
572       */
573      public double nextDouble(double origin, double bound) {
574          if (!(origin < bound))
575 <            throw new IllegalArgumentException("bound must be greater than origin");
575 >            throw new IllegalArgumentException(BadRange);
576          return internalNextDouble(origin, bound);
577      }
578  
# Line 616 | Line 589 | public class SplittableRandom {
589      // maintenance purposes the small differences across forms.
590  
591      /**
592 <     * Returns a stream producing the given {@code streamSize} number of
593 <     * pseudorandom {@code int} values.
592 >     * Returns a stream producing the given {@code streamSize} number
593 >     * of pseudorandom {@code int} values from this generator and/or
594 >     * one split from it.
595       *
596       * @param streamSize the number of values to generate
597       * @return a stream of pseudorandom {@code int} values
# Line 626 | Line 600 | public class SplittableRandom {
600       */
601      public IntStream ints(long streamSize) {
602          if (streamSize < 0L)
603 <            throw new IllegalArgumentException("negative Stream size");
603 >            throw new IllegalArgumentException(BadSize);
604          return StreamSupport.intStream
605              (new RandomIntsSpliterator
606               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 635 | Line 609 | public class SplittableRandom {
609  
610      /**
611       * Returns an effectively unlimited stream of pseudorandom {@code int}
612 <     * values.
612 >     * values from this generator and/or one split from it.
613       *
614       * @implNote This method is implemented to be equivalent to {@code
615       * ints(Long.MAX_VALUE)}.
# Line 650 | Line 624 | public class SplittableRandom {
624      }
625  
626      /**
627 <     * Returns a stream producing the given {@code streamSize} number of
628 <     * pseudorandom {@code int} values, each conforming to the given
629 <     * origin and bound.
627 >     * Returns a stream producing the given {@code streamSize} number
628 >     * of pseudorandom {@code int} values from this generator and/or one split
629 >     * from it; each value conforms to the given origin (inclusive) and bound
630 >     * (exclusive).
631       *
632       * @param streamSize the number of values to generate
633 <     * @param randomNumberOrigin the origin of each random value
634 <     * @param randomNumberBound the bound of each random value
633 >     * @param randomNumberOrigin the origin (inclusive) of each random value
634 >     * @param randomNumberBound the bound (exclusive) of each random value
635       * @return a stream of pseudorandom {@code int} values,
636 <     *         each with the given origin and bound
636 >     *         each with the given origin (inclusive) and bound (exclusive)
637       * @throws IllegalArgumentException if {@code streamSize} is
638       *         less than zero, or {@code randomNumberOrigin}
639       *         is greater than or equal to {@code randomNumberBound}
# Line 666 | Line 641 | public class SplittableRandom {
641      public IntStream ints(long streamSize, int randomNumberOrigin,
642                            int randomNumberBound) {
643          if (streamSize < 0L)
644 <            throw new IllegalArgumentException("negative Stream size");
644 >            throw new IllegalArgumentException(BadSize);
645          if (randomNumberOrigin >= randomNumberBound)
646 <            throw new IllegalArgumentException("bound must be greater than origin");
646 >            throw new IllegalArgumentException(BadRange);
647          return StreamSupport.intStream
648              (new RandomIntsSpliterator
649               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 677 | Line 652 | public class SplittableRandom {
652  
653      /**
654       * Returns an effectively unlimited stream of pseudorandom {@code
655 <     * int} values, each conforming to the given origin and bound.
655 >     * int} values from this generator and/or one split from it; each value
656 >     * conforms to the given origin (inclusive) and bound (exclusive).
657       *
658       * @implNote This method is implemented to be equivalent to {@code
659       * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
660       *
661 <     * @param randomNumberOrigin the origin of each random value
662 <     * @param randomNumberBound the bound of each random value
661 >     * @param randomNumberOrigin the origin (inclusive) of each random value
662 >     * @param randomNumberBound the bound (exclusive) of each random value
663       * @return a stream of pseudorandom {@code int} values,
664 <     *         each with the given origin and bound
664 >     *         each with the given origin (inclusive) and bound (exclusive)
665       * @throws IllegalArgumentException if {@code randomNumberOrigin}
666       *         is greater than or equal to {@code randomNumberBound}
667       */
668      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
669          if (randomNumberOrigin >= randomNumberBound)
670 <            throw new IllegalArgumentException("bound must be greater than origin");
670 >            throw new IllegalArgumentException(BadRange);
671          return StreamSupport.intStream
672              (new RandomIntsSpliterator
673               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 699 | Line 675 | public class SplittableRandom {
675      }
676  
677      /**
678 <     * Returns a stream producing the given {@code streamSize} number of
679 <     * pseudorandom {@code long} values.
678 >     * Returns a stream producing the given {@code streamSize} number
679 >     * of pseudorandom {@code long} values from this generator and/or
680 >     * one split from it.
681       *
682       * @param streamSize the number of values to generate
683       * @return a stream of pseudorandom {@code long} values
# Line 709 | Line 686 | public class SplittableRandom {
686       */
687      public LongStream longs(long streamSize) {
688          if (streamSize < 0L)
689 <            throw new IllegalArgumentException("negative Stream size");
689 >            throw new IllegalArgumentException(BadSize);
690          return StreamSupport.longStream
691              (new RandomLongsSpliterator
692               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 717 | Line 694 | public class SplittableRandom {
694      }
695  
696      /**
697 <     * Returns an effectively unlimited stream of pseudorandom {@code long}
698 <     * values.
697 >     * Returns an effectively unlimited stream of pseudorandom {@code
698 >     * long} values from this generator and/or one split from it.
699       *
700       * @implNote This method is implemented to be equivalent to {@code
701       * longs(Long.MAX_VALUE)}.
# Line 734 | Line 711 | public class SplittableRandom {
711  
712      /**
713       * Returns a stream producing the given {@code streamSize} number of
714 <     * pseudorandom {@code long} values, each conforming to the
715 <     * given origin and bound.
714 >     * pseudorandom {@code long} values from this generator and/or one split
715 >     * from it; each value conforms to the given origin (inclusive) and bound
716 >     * (exclusive).
717       *
718       * @param streamSize the number of values to generate
719 <     * @param randomNumberOrigin the origin of each random value
720 <     * @param randomNumberBound the bound of each random value
719 >     * @param randomNumberOrigin the origin (inclusive) of each random value
720 >     * @param randomNumberBound the bound (exclusive) of each random value
721       * @return a stream of pseudorandom {@code long} values,
722 <     *         each with the given origin and bound
722 >     *         each with the given origin (inclusive) and bound (exclusive)
723       * @throws IllegalArgumentException if {@code streamSize} is
724       *         less than zero, or {@code randomNumberOrigin}
725       *         is greater than or equal to {@code randomNumberBound}
# Line 749 | Line 727 | public class SplittableRandom {
727      public LongStream longs(long streamSize, long randomNumberOrigin,
728                              long randomNumberBound) {
729          if (streamSize < 0L)
730 <            throw new IllegalArgumentException("negative Stream size");
730 >            throw new IllegalArgumentException(BadSize);
731          if (randomNumberOrigin >= randomNumberBound)
732 <            throw new IllegalArgumentException("bound must be greater than origin");
732 >            throw new IllegalArgumentException(BadRange);
733          return StreamSupport.longStream
734              (new RandomLongsSpliterator
735               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 760 | Line 738 | public class SplittableRandom {
738  
739      /**
740       * Returns an effectively unlimited stream of pseudorandom {@code
741 <     * long} values, each conforming to the given origin and bound.
741 >     * long} values from this generator and/or one split from it; each value
742 >     * conforms to the given origin (inclusive) and bound (exclusive).
743       *
744       * @implNote This method is implemented to be equivalent to {@code
745       * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
746       *
747 <     * @param randomNumberOrigin the origin of each random value
748 <     * @param randomNumberBound the bound of each random value
747 >     * @param randomNumberOrigin the origin (inclusive) of each random value
748 >     * @param randomNumberBound the bound (exclusive) of each random value
749       * @return a stream of pseudorandom {@code long} values,
750 <     *         each with the given origin and bound
750 >     *         each with the given origin (inclusive) and bound (exclusive)
751       * @throws IllegalArgumentException if {@code randomNumberOrigin}
752       *         is greater than or equal to {@code randomNumberBound}
753       */
754      public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
755          if (randomNumberOrigin >= randomNumberBound)
756 <            throw new IllegalArgumentException("bound must be greater than origin");
756 >            throw new IllegalArgumentException(BadRange);
757          return StreamSupport.longStream
758              (new RandomLongsSpliterator
759               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 783 | Line 762 | public class SplittableRandom {
762  
763      /**
764       * Returns a stream producing the given {@code streamSize} number of
765 <     * pseudorandom {@code double} values, each between zero
766 <     * (inclusive) and one (exclusive).
765 >     * pseudorandom {@code double} values from this generator and/or one split
766 >     * from it; each value is between zero (inclusive) and one (exclusive).
767       *
768       * @param streamSize the number of values to generate
769       * @return a stream of {@code double} values
# Line 793 | Line 772 | public class SplittableRandom {
772       */
773      public DoubleStream doubles(long streamSize) {
774          if (streamSize < 0L)
775 <            throw new IllegalArgumentException("negative Stream size");
775 >            throw new IllegalArgumentException(BadSize);
776          return StreamSupport.doubleStream
777              (new RandomDoublesSpliterator
778               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 802 | Line 781 | public class SplittableRandom {
781  
782      /**
783       * Returns an effectively unlimited stream of pseudorandom {@code
784 <     * double} values, each between zero (inclusive) and one
785 <     * (exclusive).
784 >     * double} values from this generator and/or one split from it; each value
785 >     * is between zero (inclusive) and one (exclusive).
786       *
787       * @implNote This method is implemented to be equivalent to {@code
788       * doubles(Long.MAX_VALUE)}.
# Line 819 | Line 798 | public class SplittableRandom {
798  
799      /**
800       * Returns a stream producing the given {@code streamSize} number of
801 <     * pseudorandom {@code double} values, each conforming to the
802 <     * given origin and bound.
801 >     * pseudorandom {@code double} values from this generator and/or one split
802 >     * from it; each value conforms to the given origin (inclusive) and bound
803 >     * (exclusive).
804       *
805       * @param streamSize the number of values to generate
806 <     * @param randomNumberOrigin the origin of each random value
807 <     * @param randomNumberBound the bound of each random value
806 >     * @param randomNumberOrigin the origin (inclusive) of each random value
807 >     * @param randomNumberBound the bound (exclusive) of each random value
808       * @return a stream of pseudorandom {@code double} values,
809 <     * each with the given origin and bound
809 >     *         each with the given origin (inclusive) and bound (exclusive)
810       * @throws IllegalArgumentException if {@code streamSize} is
811 <     * less than zero
811 >     *         less than zero
812       * @throws IllegalArgumentException if {@code randomNumberOrigin}
813       *         is greater than or equal to {@code randomNumberBound}
814       */
815      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
816                                  double randomNumberBound) {
817          if (streamSize < 0L)
818 <            throw new IllegalArgumentException("negative Stream size");
818 >            throw new IllegalArgumentException(BadSize);
819          if (!(randomNumberOrigin < randomNumberBound))
820 <            throw new IllegalArgumentException("bound must be greater than origin");
820 >            throw new IllegalArgumentException(BadRange);
821          return StreamSupport.doubleStream
822              (new RandomDoublesSpliterator
823               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 846 | Line 826 | public class SplittableRandom {
826  
827      /**
828       * Returns an effectively unlimited stream of pseudorandom {@code
829 <     * double} values, each conforming to the given origin and bound.
829 >     * double} values from this generator and/or one split from it; each value
830 >     * conforms to the given origin (inclusive) and bound (exclusive).
831       *
832       * @implNote This method is implemented to be equivalent to {@code
833       * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
834       *
835 <     * @param randomNumberOrigin the origin of each random value
836 <     * @param randomNumberBound the bound of each random value
835 >     * @param randomNumberOrigin the origin (inclusive) of each random value
836 >     * @param randomNumberBound the bound (exclusive) of each random value
837       * @return a stream of pseudorandom {@code double} values,
838 <     * each with the given origin and bound
838 >     *         each with the given origin (inclusive) and bound (exclusive)
839       * @throws IllegalArgumentException if {@code randomNumberOrigin}
840       *         is greater than or equal to {@code randomNumberBound}
841       */
842      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
843          if (!(randomNumberOrigin < randomNumberBound))
844 <            throw new IllegalArgumentException("bound must be greater than origin");
844 >            throw new IllegalArgumentException(BadRange);
845          return StreamSupport.doubleStream
846              (new RandomDoublesSpliterator
847               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 918 | Line 899 | public class SplittableRandom {
899              long i = index, f = fence;
900              if (i < f) {
901                  index = f;
902 +                SplittableRandom r = rng;
903                  int o = origin, b = bound;
904                  do {
905 <                    consumer.accept(rng.internalNextInt(o, b));
905 >                    consumer.accept(r.internalNextInt(o, b));
906                  } while (++i < f);
907              }
908          }
# Line 972 | Line 954 | public class SplittableRandom {
954              long i = index, f = fence;
955              if (i < f) {
956                  index = f;
957 +                SplittableRandom r = rng;
958                  long o = origin, b = bound;
959                  do {
960 <                    consumer.accept(rng.internalNextLong(o, b));
960 >                    consumer.accept(r.internalNextLong(o, b));
961                  } while (++i < f);
962              }
963          }
# Line 1027 | Line 1010 | public class SplittableRandom {
1010              long i = index, f = fence;
1011              if (i < f) {
1012                  index = f;
1013 +                SplittableRandom r = rng;
1014                  double o = origin, b = bound;
1015                  do {
1016 <                    consumer.accept(rng.internalNextDouble(o, b));
1016 >                    consumer.accept(r.internalNextDouble(o, b));
1017                  } while (++i < f);
1018              }
1019          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines