--- jsr166/src/main/java/util/SplittableRandom.java 2013/07/12 11:26:34 1.7
+++ jsr166/src/main/java/util/SplittableRandom.java 2013/09/20 14:06:46 1.23
@@ -25,8 +25,8 @@
package java.util;
+import java.net.NetworkInterface;
import java.util.concurrent.atomic.AtomicLong;
-import java.util.Spliterator;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.DoubleConsumer;
@@ -38,10 +38,12 @@ import java.util.stream.DoubleStream;
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class SplittableRandom supports methods for
+ * generate subtasks. Class {@code SplittableRandom} supports methods for
* producing pseudorandom numbers of type {@code int}, {@code long},
* and {@code double} with similar usages as for class
- * {@link java.util.Random} but differs in the following ways:
+ * {@link java.util.Random} but differs in the following ways:
+ *
+ *
*
* - Series of generated values pass the DieHarder suite testing
* independence and uniformity properties of random number generators.
@@ -49,7 +51,9 @@ import java.util.stream.DoubleStream;
* href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
* 3.31.1.) These tests validate only the methods for certain
* types and ranges, but similar properties are expected to hold, at
- * least approximately, for others as well.
+ * least approximately, for others as well. The period
+ * (length of any series of generated values before it repeats) is at
+ * least 264.
*
* - Method {@link #split} constructs and returns a new
* SplittableRandom instance that shares no mutable state with the
@@ -72,21 +76,18 @@ import java.util.stream.DoubleStream;
*
*
*
+ * Instances of {@code SplittableRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
* @author Guy Steele
* @author Doug Lea
* @since 1.8
*/
-public class SplittableRandom {
-
- /*
- * File organization: First the non-public methods that constitute
- * the main algorithm, then the main public methods, followed by
- * some custom spliterator classes needed for stream methods.
- *
- * Credits: Primary algorithm and code by Guy Steele. Stream
- * support methods by Doug Lea. Documentation jointly produced
- * with additional help from Brian Goetz.
- */
+public final class SplittableRandom {
/*
* Implementation Overview.
@@ -94,199 +95,184 @@ public class SplittableRandom {
* This algorithm was inspired by the "DotMix" algorithm by
* Leiserson, Schardl, and Sukha "Deterministic Parallel
* Random-Number Generation for Dynamic-Multithreading Platforms",
- * PPoPP 2012, but improves and extends it in several ways.
+ * PPoPP 2012, as well as those in "Parallel random numbers: as
+ * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It
+ * differs mainly in simplifying and cheapening operations.
+ *
+ * The primary update step (method nextSeed()) is to add a
+ * constant ("gamma") to the current (64 bit) seed, forming a
+ * simple sequence. The seed and the gamma values for any two
+ * SplittableRandom instances are highly likely to be different.
+ *
+ * Methods nextLong, nextInt, and derivatives do not return the
+ * sequence (seed) values, but instead a hash-like bit-mix of
+ * their bits, producing more independently distributed sequences.
+ * For nextLong, the mix64 function is based on David Stafford's
+ * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
+ * "Mix13" variant of the "64-bit finalizer" function in Austin
+ * Appleby's MurmurHash3 algorithm See
+ * http://code.google.com/p/smhasher/wiki/MurmurHash3 . The mix32
+ * function is based on Stafford's Mix04 mix function, but returns
+ * the upper 32 bits cast as int.
+ *
+ * The split operation uses the current generator to form the seed
+ * and gamma for another SplittableRandom. To conservatively
+ * avoid potential correlations between seed and value generation,
+ * gamma selection (method mixGamma) uses different
+ * (Murmurhash3's) mix constants. To avoid potential weaknesses
+ * in bit-mixing transformations, we restrict gammas to odd values
+ * with at least 24 0-1 or 1-0 bit transitions. Rather than
+ * rejecting candidates with too few or too many bits set, method
+ * mixGamma flips some bits (which has the effect of mapping at
+ * most 4 to any given gamma value). This reduces the effective
+ * set of 64bit odd gamma values by about 2%, and serves as an
+ * automated screening for sequence constant selection that is
+ * left as an empirical decision in some other hashing and crypto
+ * algorithms.
+ *
+ * The resulting generator thus transforms a sequence in which
+ * (typically) many bits change on each step, with an inexpensive
+ * mixer with good (but less than cryptographically secure)
+ * avalanching.
+ *
+ * The default (no-argument) constructor, in essence, invokes
+ * split() for a common "defaultGen" SplittableRandom. Unlike
+ * other cases, this split must be performed in a thread-safe
+ * manner, so we use an AtomicLong to represent the seed rather
+ * than use an explicit SplittableRandom. To bootstrap the
+ * defaultGen, we start off using a seed based on current time and
+ * network interface address unless the java.util.secureRandomSeed
+ * property is set. This serves as a slimmed-down (and insecure)
+ * variant of SecureRandom that also avoids stalls that may occur
+ * when using /dev/random.
+ *
+ * It is a relatively simple matter to apply the basic design here
+ * to use 128 bit seeds. However, emulating 128bit arithmetic and
+ * carrying around twice the state add more overhead than appears
+ * warranted for current usages.
*
- * The primary update step (see method nextSeed()) is simply to
- * add a constant ("gamma") to the current seed, modulo a prime
- * ("George"). However, the nextLong and nextInt methods do not
- * return this value, but instead the results of bit-mixing
- * transformations that produce more uniformly distributed
- * sequences.
- *
- * "George" is the otherwise nameless (because it cannot be
- * represented) prime number 2^64+13. Using a prime number larger
- * than can fit in a long ensures that all possible long values
- * can occur, plus 13 others that just get skipped over when they
- * are encountered; see method addGammaModGeorge. For this to
- * work, initial gamma values must be at least 13.
- *
- * The value of gamma differs for each instance across a series of
- * splits, and is generated using a slightly stripped-down variant
- * of the same algorithm, but operating across calls to split(),
- * not calls to nextSeed(): Each instance carries the state of
- * this generator as nextSplit, and uses mix64(nextSplit) as its
- * own gamma value. Computations of gammas themselves use a fixed
- * constant as the second argument to the addGammaModGeorge
- * function, GAMMA_GAMMA, a "genuinely random" number from a
- * radioactive decay reading (obtained from
- * http://www.fourmilab.ch/hotbits/) meeting the above range
- * constraint. Using a fixed constant maintains the invariant that
- * the value of gamma is the same for every instance that is at
- * the same split-distance from their common root. (Note: there is
- * nothing especially magic about obtaining this constant from a
- * "truly random" physical source rather than just choosing one
- * arbitrarily; using "hotbits" was merely an aesthetically pleasing
- * choice. In either case, good statistical behavior of the
- * algorithm should be, and was, verified by using the DieHarder
- * test suite.)
- *
- * The mix64 bit-mixing function called by nextLong and other
- * methods computes the same value as the "64-bit finalizer"
- * function in Austin Appleby's MurmurHash3 algorithm. See
- * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
- * comments: "The constants for the finalizers were generated by a
- * simple simulated-annealing algorithm, and both avalanche all
- * bits of 'h' to within 0.25% bias." It also appears to work to
- * use instead any of the variants proposed by David Stafford at
- * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
- * but these variants have not yet been tested as thoroughly
- * in the context of the implementation of SplittableRandom.
- *
- * The mix32 function used for nextInt just consists of two of the
- * five lines of mix64; avalanche testing shows that the 64-bit result
- * has its top 32 bits avalanched well, though not the bottom 32 bits.
- * DieHarder tests show that it is adequate for generating one
- * random int from the 64-bit result of nextSeed.
- *
- * Support for the default (no-argument) constructor relies on an
- * AtomicLong (defaultSeedGenerator) to help perform the
- * equivalent of a split of a statically constructed
- * SplittableRandom. Unlike other cases, this split must be
- * performed in a thread-safe manner. We use
- * AtomicLong.compareAndSet as the (typically) most efficient
- * mechanism. To bootstrap, we start off using System.nanotime(),
- * and update using another "genuinely random" constant
- * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
- * not 0, for its splitSeed argument (addGammaModGeorge(0,
- * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
- * this root generator, even though the root is not explicitly
- * represented as a SplittableRandom.
- */
-
- /**
- * The "genuinely random" value for producing new gamma values.
- * The value is arbitrary, subject to the requirement that it be
- * greater or equal to 13.
- */
- private static final long GAMMA_GAMMA = 0xF2281E2DBA6606F3L;
-
- /**
- * The "genuinely random" seed update value for default constructors.
- * The value is arbitrary, subject to the requirement that it be
- * greater or equal to 13.
+ * File organization: First the non-public methods that constitute
+ * the main algorithm, then the main public methods, followed by
+ * some custom spliterator classes needed for stream methods.
*/
- private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
/**
- * The least non-zero value returned by nextDouble(). This value
- * is scaled by a random value of 53 bits to produce a result.
+ * The golden ratio scaled to 64bits, used as the initial gamma
+ * value for (unsplit) SplittableRandoms.
*/
- private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
+ private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
/**
- * The next seed for default constructors.
+ * The least non-zero value returned by nextDouble(). This value
+ * is scaled by a random value of 53 bits to produce a result.
*/
- private static final AtomicLong defaultSeedGenerator =
- new AtomicLong(System.nanoTime());
+ private static final double DOUBLE_ULP = 1.0 / (1L << 53);
/**
- * The seed, updated only via method nextSeed.
+ * The seed. Updated only via method nextSeed.
*/
private long seed;
/**
- * The constant value added to seed (mod George) on each update.
+ * The step value.
*/
private final long gamma;
/**
- * The next seed to use for splits. Propagated using
- * addGammaModGeorge across instances.
+ * Internal constructor used by all others except default constructor.
*/
- private final long nextSplit;
-
- /**
- * Adds the given gamma value, g, to the given seed value s, mod
- * George (2^64+13). We regard s and g as unsigned values
- * (ranging from 0 to 2^64-1). We add g to s either once or twice
- * (mod George) as necessary to produce an (unsigned) result less
- * than 2^64. We require that g must be at least 13. This
- * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
- * George < 2^64; thus we need only a conditional, not a loop,
- * to be sure of getting a representable value.
- *
- * @param s a seed value
- * @param g a gamma value, 13 <= g (as unsigned)
- */
- private static long addGammaModGeorge(long s, long g) {
- long p = s + g;
- if (Long.compareUnsigned(p, g) >= 0)
- return p;
- long q = p - 13L;
- return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
+ private SplittableRandom(long seed, long gamma) {
+ this.seed = seed;
+ this.gamma = gamma;
}
/**
- * Returns a bit-mixed transformation of its argument.
- * See above for explanation.
+ * Computes Stafford variant 13 of 64bit mix function.
*/
private static long mix64(long z) {
- z ^= (z >>> 33);
- z *= 0xff51afd7ed558ccdL;
- z ^= (z >>> 33);
- z *= 0xc4ceb9fe1a85ec53L;
- z ^= (z >>> 33);
- return z;
+ z *= 0xbf58476d1ce4e5b9L;
+ z = (z ^ (z >>> 32)) * 0x94d049bb133111ebL;
+ return z ^ (z >>> 32);
}
/**
- * Returns a bit-mixed int transformation of its argument.
- * See above for explanation.
+ * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
*/
private static int mix32(long z) {
- z ^= (z >>> 33);
- z *= 0xc4ceb9fe1a85ec53L;
- return (int)(z >>> 32);
+ z *= 0x62a9d9ed799705f5L;
+ return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
/**
- * Internal constructor used by all other constructors and by
- * method split. Establishes the initial seed for this instance,
- * and uses the given splitSeed to establish gamma, as well as the
- * nextSplit to use by this instance. The loop to skip ineligible
- * gammas very rarely iterates, and does so at most 13 times.
+ * Returns the gamma value to use for a new split instance.
*/
- private SplittableRandom(long seed, long splitSeed) {
- this.seed = seed;
- long s = splitSeed, g;
- do { // ensure gamma >= 13, considered as an unsigned integer
- s = addGammaModGeorge(s, GAMMA_GAMMA);
- g = mix64(s);
- } while (Long.compareUnsigned(g, 13L) < 0);
- this.gamma = g;
- this.nextSplit = s;
+ private static long mixGamma(long z) {
+ z *= 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
+ z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
+ z = (z ^ (z >>> 33)) | 1L; // force to be odd
+ int n = Long.bitCount(z ^ (z >>> 1)); // ensure enough transitions
+ return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
}
/**
- * Updates in-place and returns seed.
- * See above for explanation.
+ * Adds gamma to seed.
*/
private long nextSeed() {
- return seed = addGammaModGeorge(seed, gamma);
+ return seed += gamma;
}
/**
- * Atomically updates and returns next seed for default constructor.
+ * The seed generator for default constructors.
*/
- private static long nextDefaultSeed() {
- long oldSeed, newSeed;
- do {
- oldSeed = defaultSeedGenerator.get();
- newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
- } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
- return mix64(newSeed);
+ private static final AtomicLong defaultGen = new AtomicLong(initialSeed());
+
+ private static long initialSeed() {
+ String pp = java.security.AccessController.doPrivileged(
+ new sun.security.action.GetPropertyAction(
+ "java.util.secureRandomSeed"));
+ if (pp != null && pp.equalsIgnoreCase("true")) {
+ byte[] seedBytes = java.security.SecureRandom.getSeed(8);
+ long s = (long)(seedBytes[0]) & 0xffL;
+ for (int i = 1; i < 8; ++i)
+ s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
+ return s;
+ }
+ long h = 0L;
+ try {
+ Enumeration ifcs =
+ NetworkInterface.getNetworkInterfaces();
+ boolean retry = false; // retry once if getHardwareAddress is null
+ while (ifcs.hasMoreElements()) {
+ NetworkInterface ifc = ifcs.nextElement();
+ if (!ifc.isVirtual()) { // skip fake addresses
+ byte[] bs = ifc.getHardwareAddress();
+ if (bs != null) {
+ int n = bs.length;
+ int m = Math.min(n >>> 1, 4);
+ for (int i = 0; i < m; ++i)
+ h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
+ if (m < 4)
+ h = (h << 8) ^ bs[n-1-m];
+ h = mix64(h);
+ break;
+ }
+ else if (!retry)
+ retry = true;
+ else
+ break;
+ }
+ }
+ } catch (Exception ignore) {
+ }
+ return (h ^ mix64(System.currentTimeMillis()) ^
+ mix64(System.nanoTime()));
}
+ // IllegalArgumentException messages
+ static final String BadBound = "bound must be positive";
+ static final String BadRange = "bound must be greater than origin";
+ static final String BadSize = "size must be non-negative";
+
/*
* Internal versions of nextX methods used by streams, as well as
* the public nextX(origin, bound) methods. These exist mainly to
@@ -362,7 +348,7 @@ public class SplittableRandom {
int r = mix32(nextSeed());
if (origin < bound) {
int n = bound - origin, m = n - 1;
- if ((n & m) == 0L)
+ if ((n & m) == 0)
r = (r & m) + origin;
else if (n > 0) {
for (int u = r >>> 1;
@@ -387,7 +373,7 @@ public class SplittableRandom {
* @return a pseudorandom value
*/
final double internalNextDouble(double origin, double bound) {
- double r = (nextLong() >>> 11) * DOUBLE_UNIT;
+ double r = (nextLong() >>> 11) * DOUBLE_ULP;
if (origin < bound) {
r = r * (bound - origin) + origin;
if (r >= bound) // correct for rounding
@@ -401,12 +387,12 @@ public class SplittableRandom {
/**
* Creates a new SplittableRandom instance using the specified
* initial seed. SplittableRandom instances created with the same
- * seed generate identical sequences of values.
+ * seed in the same program generate identical sequences of values.
*
* @param seed the initial seed
*/
public SplittableRandom(long seed) {
- this(seed, 0);
+ this(seed, GOLDEN_GAMMA);
}
/**
@@ -415,8 +401,10 @@ public class SplittableRandom {
* of those of any other instances in the current program; and
* may, and typically does, vary across program invocations.
*/
- public SplittableRandom() {
- this(nextDefaultSeed(), GAMMA_GAMMA);
+ public SplittableRandom() { // emulate defaultGen.split()
+ long s = defaultGen.getAndAdd(2 * GOLDEN_GAMMA);
+ this.seed = mix64(s);
+ this.gamma = mixGamma(s + GOLDEN_GAMMA);
}
/**
@@ -434,7 +422,7 @@ public class SplittableRandom {
* @return the new SplittableRandom instance
*/
public SplittableRandom split() {
- return new SplittableRandom(nextSeed(), nextSplit);
+ return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
}
/**
@@ -450,19 +438,18 @@ public class SplittableRandom {
* Returns a pseudorandom {@code int} value between zero (inclusive)
* and the specified bound (exclusive).
*
- * @param bound the bound on the random number to be returned. Must be
- * positive.
+ * @param bound the upper bound (exclusive). Must be positive.
* @return a pseudorandom {@code int} value between zero
- * (inclusive) and the bound (exclusive).
- * @throws IllegalArgumentException if the bound is less than zero
+ * (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
*/
public int nextInt(int bound) {
if (bound <= 0)
- throw new IllegalArgumentException("bound must be positive");
+ throw new IllegalArgumentException(BadBound);
// Specialize internalNextInt for origin 0
int r = mix32(nextSeed());
int m = bound - 1;
- if ((bound & m) == 0L) // power of two
+ if ((bound & m) == 0) // power of two
r &= m;
else { // reject over-represented candidates
for (int u = r >>> 1;
@@ -480,13 +467,13 @@ public class SplittableRandom {
* @param origin the least value returned
* @param bound the upper bound (exclusive)
* @return a pseudorandom {@code int} value between the origin
- * (inclusive) and the bound (exclusive).
+ * (inclusive) and the bound (exclusive)
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
public int nextInt(int origin, int bound) {
if (origin >= bound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return internalNextInt(origin, bound);
}
@@ -503,15 +490,14 @@ public class SplittableRandom {
* Returns a pseudorandom {@code long} value between zero (inclusive)
* and the specified bound (exclusive).
*
- * @param bound the bound on the random number to be returned. Must be
- * positive.
+ * @param bound the upper bound (exclusive). Must be positive.
* @return a pseudorandom {@code long} value between zero
- * (inclusive) and the bound (exclusive).
- * @throws IllegalArgumentException if {@code bound} is less than zero
+ * (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
*/
public long nextLong(long bound) {
if (bound <= 0)
- throw new IllegalArgumentException("bound must be positive");
+ throw new IllegalArgumentException(BadBound);
// Specialize internalNextLong for origin 0
long r = mix64(nextSeed());
long m = bound - 1;
@@ -533,13 +519,13 @@ public class SplittableRandom {
* @param origin the least value returned
* @param bound the upper bound (exclusive)
* @return a pseudorandom {@code long} value between the origin
- * (inclusive) and the bound (exclusive).
+ * (inclusive) and the bound (exclusive)
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
public long nextLong(long origin, long bound) {
if (origin >= bound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return internalNextLong(origin, bound);
}
@@ -548,26 +534,25 @@ public class SplittableRandom {
* (inclusive) and one (exclusive).
*
* @return a pseudorandom {@code double} value between zero
- * (inclusive) and one (exclusive)
+ * (inclusive) and one (exclusive)
*/
public double nextDouble() {
- return (nextLong() >>> 11) * DOUBLE_UNIT;
+ return (mix64(nextSeed()) >>> 11) * DOUBLE_ULP;
}
/**
* Returns a pseudorandom {@code double} value between 0.0
* (inclusive) and the specified bound (exclusive).
*
- * @param bound the bound on the random number to be returned. Must be
- * positive.
+ * @param bound the upper bound (exclusive). Must be positive.
* @return a pseudorandom {@code double} value between zero
- * (inclusive) and the bound (exclusive).
- * @throws IllegalArgumentException if {@code bound} is less than zero
+ * (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
*/
public double nextDouble(double bound) {
if (!(bound > 0.0))
- throw new IllegalArgumentException("bound must be positive");
- double result = nextDouble() * bound;
+ throw new IllegalArgumentException(BadBound);
+ double result = (mix64(nextSeed()) >>> 11) * DOUBLE_ULP * bound;
return (result < bound) ? result : // correct for rounding
Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
}
@@ -577,24 +562,34 @@ public class SplittableRandom {
* origin (inclusive) and bound (exclusive).
*
* @param origin the least value returned
- * @param bound the upper bound
+ * @param bound the upper bound (exclusive)
* @return a pseudorandom {@code double} value between the origin
- * (inclusive) and the bound (exclusive).
+ * (inclusive) and the bound (exclusive)
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
public double nextDouble(double origin, double bound) {
if (!(origin < bound))
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return internalNextDouble(origin, bound);
}
+ /**
+ * Returns a pseudorandom {@code boolean} value.
+ *
+ * @return a pseudorandom {@code boolean} value
+ */
+ public boolean nextBoolean() {
+ return mix32(nextSeed()) < 0;
+ }
+
// stream methods, coded in a way intended to better isolate for
// maintenance purposes the small differences across forms.
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code int} values.
+ * Returns a stream producing the given {@code streamSize} number
+ * of pseudorandom {@code int} values from this generator and/or
+ * one split from it.
*
* @param streamSize the number of values to generate
* @return a stream of pseudorandom {@code int} values
@@ -603,7 +598,7 @@ public class SplittableRandom {
*/
public IntStream ints(long streamSize) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
return StreamSupport.intStream
(new RandomIntsSpliterator
(this, 0L, streamSize, Integer.MAX_VALUE, 0),
@@ -612,7 +607,7 @@ public class SplittableRandom {
/**
* Returns an effectively unlimited stream of pseudorandom {@code int}
- * values
+ * values from this generator and/or one split from it.
*
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE)}.
@@ -627,15 +622,16 @@ public class SplittableRandom {
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code int} values, each conforming to the given
- * origin and bound.
+ * Returns a stream producing the given {@code streamSize} number
+ * of pseudorandom {@code int} values from this generator and/or one split
+ * from it; each value conforms to the given origin (inclusive) and bound
+ * (exclusive).
*
* @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code int} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
@@ -643,9 +639,9 @@ public class SplittableRandom {
public IntStream ints(long streamSize, int randomNumberOrigin,
int randomNumberBound) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.intStream
(new RandomIntsSpliterator
(this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
@@ -654,21 +650,22 @@ public class SplittableRandom {
/**
* Returns an effectively unlimited stream of pseudorandom {@code
- * int} values, each conforming to the given origin and bound.
+ * int} values from this generator and/or one split from it; each value
+ * conforms to the given origin (inclusive) and bound (exclusive).
*
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code int} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.intStream
(new RandomIntsSpliterator
(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
@@ -676,8 +673,9 @@ public class SplittableRandom {
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long} values.
+ * Returns a stream producing the given {@code streamSize} number
+ * of pseudorandom {@code long} values from this generator and/or
+ * one split from it.
*
* @param streamSize the number of values to generate
* @return a stream of pseudorandom {@code long} values
@@ -686,7 +684,7 @@ public class SplittableRandom {
*/
public LongStream longs(long streamSize) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
return StreamSupport.longStream
(new RandomLongsSpliterator
(this, 0L, streamSize, Long.MAX_VALUE, 0L),
@@ -694,8 +692,8 @@ public class SplittableRandom {
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code long}
- * values.
+ * Returns an effectively unlimited stream of pseudorandom {@code
+ * long} values from this generator and/or one split from it.
*
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE)}.
@@ -711,14 +709,15 @@ public class SplittableRandom {
/**
* Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long} values, each conforming to the
- * given origin and bound.
+ * pseudorandom {@code long} values from this generator and/or one split
+ * from it; each value conforms to the given origin (inclusive) and bound
+ * (exclusive).
*
* @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code long} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
@@ -726,9 +725,9 @@ public class SplittableRandom {
public LongStream longs(long streamSize, long randomNumberOrigin,
long randomNumberBound) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.longStream
(new RandomLongsSpliterator
(this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
@@ -737,21 +736,22 @@ public class SplittableRandom {
/**
* Returns an effectively unlimited stream of pseudorandom {@code
- * long} values, each conforming to the given origin and bound.
+ * long} values from this generator and/or one split from it; each value
+ * conforms to the given origin (inclusive) and bound (exclusive).
*
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code long} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.longStream
(new RandomLongsSpliterator
(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
@@ -760,8 +760,8 @@ public class SplittableRandom {
/**
* Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each between zero
- * (inclusive) and one (exclusive).
+ * pseudorandom {@code double} values from this generator and/or one split
+ * from it; each value is between zero (inclusive) and one (exclusive).
*
* @param streamSize the number of values to generate
* @return a stream of {@code double} values
@@ -770,7 +770,7 @@ public class SplittableRandom {
*/
public DoubleStream doubles(long streamSize) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
return StreamSupport.doubleStream
(new RandomDoublesSpliterator
(this, 0L, streamSize, Double.MAX_VALUE, 0.0),
@@ -779,8 +779,8 @@ public class SplittableRandom {
/**
* Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each between zero (inclusive) and one
- * (exclusive).
+ * double} values from this generator and/or one split from it; each value
+ * is between zero (inclusive) and one (exclusive).
*
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE)}.
@@ -796,25 +796,26 @@ public class SplittableRandom {
/**
* Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each conforming to the
- * given origin and bound.
+ * pseudorandom {@code double} values from this generator and/or one split
+ * from it; each value conforms to the given origin (inclusive) and bound
+ * (exclusive).
*
* @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code double} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code streamSize} is
- * less than zero.
+ * less than zero
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
public DoubleStream doubles(long streamSize, double randomNumberOrigin,
double randomNumberBound) {
if (streamSize < 0L)
- throw new IllegalArgumentException("negative Stream size");
+ throw new IllegalArgumentException(BadSize);
if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.doubleStream
(new RandomDoublesSpliterator
(this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
@@ -823,21 +824,22 @@ public class SplittableRandom {
/**
* Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each conforming to the given origin and bound.
+ * double} values from this generator and/or one split from it; each value
+ * conforms to the given origin (inclusive) and bound (exclusive).
*
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*
- * @param randomNumberOrigin the origin of each random value
- * @param randomNumberBound the bound of each random value
+ * @param randomNumberOrigin the origin (inclusive) of each random value
+ * @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code double} values,
- * each with the given origin and bound.
+ * each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException("bound must be greater than origin");
+ throw new IllegalArgumentException(BadRange);
return StreamSupport.doubleStream
(new RandomDoublesSpliterator
(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
@@ -852,7 +854,7 @@ public class SplittableRandom {
* approach. The long and double versions of this class are
* identical except for types.
*/
- static class RandomIntsSpliterator implements Spliterator.OfInt {
+ static final class RandomIntsSpliterator implements Spliterator.OfInt {
final SplittableRandom rng;
long index;
final long fence;
@@ -895,9 +897,10 @@ public class SplittableRandom {
long i = index, f = fence;
if (i < f) {
index = f;
+ SplittableRandom r = rng;
int o = origin, b = bound;
do {
- consumer.accept(rng.internalNextInt(o, b));
+ consumer.accept(r.internalNextInt(o, b));
} while (++i < f);
}
}
@@ -906,7 +909,7 @@ public class SplittableRandom {
/**
* Spliterator for long streams.
*/
- static class RandomLongsSpliterator implements Spliterator.OfLong {
+ static final class RandomLongsSpliterator implements Spliterator.OfLong {
final SplittableRandom rng;
long index;
final long fence;
@@ -949,9 +952,10 @@ public class SplittableRandom {
long i = index, f = fence;
if (i < f) {
index = f;
+ SplittableRandom r = rng;
long o = origin, b = bound;
do {
- consumer.accept(rng.internalNextLong(o, b));
+ consumer.accept(r.internalNextLong(o, b));
} while (++i < f);
}
}
@@ -961,7 +965,7 @@ public class SplittableRandom {
/**
* Spliterator for double streams.
*/
- static class RandomDoublesSpliterator implements Spliterator.OfDouble {
+ static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
final SplittableRandom rng;
long index;
final long fence;
@@ -1004,13 +1008,13 @@ public class SplittableRandom {
long i = index, f = fence;
if (i < f) {
index = f;
+ SplittableRandom r = rng;
double o = origin, b = bound;
do {
- consumer.accept(rng.internalNextDouble(o, b));
+ consumer.accept(r.internalNextDouble(o, b));
} while (++i < f);
}
}
}
}
-