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.20 by jsr166, Sat Aug 24 06:20:15 2013 UTC vs.
Revision 1.39 by jsr166, Mon Feb 20 22:07:50 2017 UTC

# Line 25 | Line 25
25  
26   package java.util;
27  
28 import java.security.SecureRandom;
29 import java.net.InetAddress;
28   import java.util.concurrent.atomic.AtomicLong;
29 + import java.util.function.DoubleConsumer;
30   import java.util.function.IntConsumer;
31   import java.util.function.LongConsumer;
32 < import java.util.function.DoubleConsumer;
34 < import java.util.stream.StreamSupport;
32 > import java.util.stream.DoubleStream;
33   import java.util.stream.IntStream;
34   import java.util.stream.LongStream;
35 < import java.util.stream.DoubleStream;
35 > import java.util.stream.StreamSupport;
36  
37   /**
38   * A generator of uniform pseudorandom values applicable for use in
# Line 54 | Line 52 | import java.util.stream.DoubleStream;
52   * types and ranges, but similar properties are expected to hold, at
53   * least approximately, for others as well. The <em>period</em>
54   * (length of any series of generated values before it repeats) is at
55 < * least 2<sup>64</sup>. </li>
55 > * least 2<sup>64</sup>.
56   *
57 < * <li> Method {@link #split} constructs and returns a new
57 > * <li>Method {@link #split} constructs and returns a new
58   * SplittableRandom instance that shares no mutable state with the
59   * current instance. However, with very high probability, the
60   * values collectively generated by the two objects have the same
61   * statistical properties as if the same quantity of values were
62   * generated by a single thread using a single {@code
63 < * SplittableRandom} object.  </li>
63 > * SplittableRandom} object.
64   *
65   * <li>Instances of SplittableRandom are <em>not</em> thread-safe.
66   * They are designed to be split, not shared, across threads. For
# Line 73 | Line 71 | import java.util.stream.DoubleStream;
71   *
72   * <li>This class provides additional methods for generating random
73   * streams, that employ the above techniques when used in {@code
74 < * stream.parallel()} mode.</li>
74 > * stream.parallel()} mode.
75   *
76   * </ul>
77   *
# Line 88 | Line 86 | import java.util.stream.DoubleStream;
86   * @author  Doug Lea
87   * @since   1.8
88   */
89 < public class SplittableRandom {
89 > public final class SplittableRandom {
90  
91      /*
92       * Implementation Overview.
# Line 108 | Line 106 | public class SplittableRandom {
106       * Methods nextLong, nextInt, and derivatives do not return the
107       * sequence (seed) values, but instead a hash-like bit-mix of
108       * their bits, producing more independently distributed sequences.
109 <     * For nextLong, the mix64 bit-mixing function computes the same
110 <     * value as the "64-bit finalizer" function in Austin Appleby's
111 <     * MurmurHash3 algorithm.  See
112 <     * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
113 <     * comments: "The constants for the finalizers were generated by a
114 <     * simple simulated-annealing algorithm, and both avalanche all
115 <     * bits of 'h' to within 0.25% bias." The mix32 function is
118 <     * equivalent to (int)(mix64(seed) >>> 32), but faster because it
119 <     * omits a step that doesn't contribute to result.
109 >     * For nextLong, the mix64 function is based on David Stafford's
110 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
111 >     * "Mix13" variant of the "64-bit finalizer" function in Austin
112 >     * Appleby's MurmurHash3 algorithm (see
113 >     * http://code.google.com/p/smhasher/wiki/MurmurHash3). The mix32
114 >     * function is based on Stafford's Mix04 mix function, but returns
115 >     * the upper 32 bits cast as int.
116       *
117       * The split operation uses the current generator to form the seed
118       * and gamma for another SplittableRandom.  To conservatively
119       * avoid potential correlations between seed and value generation,
120 <     * gamma selection (method nextGamma) uses the "Mix13" constants
121 <     * for MurmurHash3 described by David Stafford
122 <     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
123 <     * To avoid potential weaknesses in bit-mixing transformations, we
124 <     * restrict gammas to odd values with at least 12 and no more than
125 <     * 52 bits set.  Rather than rejecting candidates with too few or
126 <     * too many bits set, method nextGamma flips some bits (which has
127 <     * the effect of mapping at most 4 to any given gamma value).
132 <     * This reduces the effective set of 64bit odd gamma values by
133 <     * about 2<sup>14</sup>, a very tiny percentage, and serves as an
120 >     * gamma selection (method mixGamma) uses different
121 >     * (Murmurhash3's) mix constants.  To avoid potential weaknesses
122 >     * in bit-mixing transformations, we restrict gammas to odd values
123 >     * with at least 24 0-1 or 1-0 bit transitions.  Rather than
124 >     * rejecting candidates with too few or too many bits set, method
125 >     * mixGamma flips some bits (which has the effect of mapping at
126 >     * most 4 to any given gamma value).  This reduces the effective
127 >     * set of 64bit odd gamma values by about 2%, and serves as an
128       * automated screening for sequence constant selection that is
129       * left as an empirical decision in some other hashing and crypto
130       * algorithms.
# Line 141 | Line 135 | public class SplittableRandom {
135       * avalanching.
136       *
137       * The default (no-argument) constructor, in essence, invokes
138 <     * split() for a common "seeder" SplittableRandom.  Unlike other
139 <     * cases, this split must be performed in a thread-safe manner, so
140 <     * we use an AtomicLong to represent the seed rather than use an
141 <     * explicit SplittableRandom. To bootstrap the seeder, we start
142 <     * off using a seed based on current time and host unless the
143 <     * java.util.secureRandomSeed property is set. This serves as a
144 <     * slimmed-down (and insecure) variant of SecureRandom that also
145 <     * avoids stalls that may occur when using /dev/random.
138 >     * split() for a common "defaultGen" SplittableRandom.  Unlike
139 >     * other cases, this split must be performed in a thread-safe
140 >     * manner, so we use an AtomicLong to represent the seed rather
141 >     * than use an explicit SplittableRandom. To bootstrap the
142 >     * defaultGen, we start off using a seed based on current time
143 >     * unless the java.util.secureRandomSeed property is set. This
144 >     * serves as a slimmed-down (and insecure) variant of SecureRandom
145 >     * that also avoids stalls that may occur when using /dev/random.
146       *
147       * It is a relatively simple matter to apply the basic design here
148       * to use 128 bit seeds. However, emulating 128bit arithmetic and
# Line 161 | Line 155 | public class SplittableRandom {
155       */
156  
157      /**
158 <     * The initial gamma value for (unsplit) SplittableRandoms. Must
159 <     * be odd with at least 12 and no more than 52 bits set. Currently
166 <     * set to the golden ratio scaled to 64bits.
158 >     * The golden ratio scaled to 64bits, used as the initial gamma
159 >     * value for (unsplit) SplittableRandoms.
160       */
161 <    private static final long INITIAL_GAMMA = 0x9e3779b97f4a7c15L;
161 >    private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
162  
163      /**
164       * The least non-zero value returned by nextDouble(). This value
165       * is scaled by a random value of 53 bits to produce a result.
166       */
167 <    private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
167 >    private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53);
168  
169      /**
170       * The seed. Updated only via method nextSeed.
# Line 192 | Line 185 | public class SplittableRandom {
185      }
186  
187      /**
188 <     * Computes MurmurHash3 64bit mix function.
188 >     * Computes Stafford variant 13 of 64bit mix function.
189       */
190      private static long mix64(long z) {
191 <        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
192 <        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
193 <        return z ^ (z >>> 33);
191 >        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
192 >        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
193 >        return z ^ (z >>> 31);
194      }
195  
196      /**
197 <     * Returns the 32 high bits of mix64(z) as int.
197 >     * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
198       */
199      private static int mix32(long z) {
200 <        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
201 <        return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
200 >        z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L;
201 >        return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
202      }
203  
204      /**
205       * Returns the gamma value to use for a new split instance.
206       */
207 <    private static long nextGamma(long z) {
208 <        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; // Stafford "Mix13"
209 <        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
210 <        z = (z ^ (z >>> 31)) | 1L; // force to be odd
211 <        int n = Long.bitCount(z);  // ensure enough 0 and 1 bits
212 <        return (n < 12 || n > 52) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
207 >    private static long mixGamma(long z) {
208 >        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
209 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
210 >        z = (z ^ (z >>> 33)) | 1L;                  // force to be odd
211 >        int n = Long.bitCount(z ^ (z >>> 1));       // ensure enough transitions
212 >        return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
213      }
214  
215      /**
# Line 226 | Line 219 | public class SplittableRandom {
219          return seed += gamma;
220      }
221  
222 +    // IllegalArgumentException messages
223 +    static final String BAD_BOUND = "bound must be positive";
224 +    static final String BAD_RANGE = "bound must be greater than origin";
225 +    static final String BAD_SIZE  = "size must be non-negative";
226 +
227      /**
228       * The seed generator for default constructors.
229       */
230 <    private static final AtomicLong seeder = new AtomicLong(initialSeed());
231 <
232 <    private static long initialSeed() {
233 <        try {  // ignore exceptions in accessing/parsing properties
234 <            String pp = System.getProperty
235 <                ("java.util.secureRandomSeed");
236 <            if (pp != null && pp.equalsIgnoreCase("true")) {
237 <                byte[] seedBytes = java.security.SecureRandom.getSeed(8);
238 <                long s = (long)(seedBytes[0]) & 0xffL;
239 <                for (int i = 1; i < 8; ++i)
240 <                    s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
241 <                return s;
242 <            }
243 <        } catch (Exception ignore) {
244 <        }
245 <        int hh = 0; // hashed host address
248 <        try {
249 <            hh = InetAddress.getLocalHost().hashCode();
250 <        } catch (Exception ignore) {
230 >    private static final AtomicLong defaultGen
231 >        = new AtomicLong(mix64(System.currentTimeMillis()) ^
232 >                         mix64(System.nanoTime()));
233 >
234 >    // at end of <clinit> to survive static initialization circularity
235 >    static {
236 >        if (java.security.AccessController.doPrivileged(
237 >            new java.security.PrivilegedAction<Boolean>() {
238 >                public Boolean run() {
239 >                    return Boolean.getBoolean("java.util.secureRandomSeed");
240 >                }})) {
241 >            byte[] seedBytes = java.security.SecureRandom.getSeed(8);
242 >            long s = (long)seedBytes[0] & 0xffL;
243 >            for (int i = 1; i < 8; ++i)
244 >                s = (s << 8) | ((long)seedBytes[i] & 0xffL);
245 >            defaultGen.set(s);
246          }
252        return (mix64((((long)hh) << 32) ^ System.currentTimeMillis()) ^
253                mix64(System.nanoTime()));
247      }
248  
256    // IllegalArgumentException messages
257    static final String BadBound = "bound must be positive";
258    static final String BadRange = "bound must be greater than origin";
259    static final String BadSize  = "size must be non-negative";
260
249      /*
250       * Internal versions of nextX methods used by streams, as well as
251       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 377 | Line 365 | public class SplittableRandom {
365       * @param seed the initial seed
366       */
367      public SplittableRandom(long seed) {
368 <        this(seed, INITIAL_GAMMA);
368 >        this(seed, GOLDEN_GAMMA);
369      }
370  
371      /**
# Line 386 | Line 374 | public class SplittableRandom {
374       * of those of any other instances in the current program; and
375       * may, and typically does, vary across program invocations.
376       */
377 <    public SplittableRandom() { // emulate seeder.split()
378 <        this.gamma = nextGamma(this.seed = seeder.addAndGet(INITIAL_GAMMA));
377 >    public SplittableRandom() { // emulate defaultGen.split()
378 >        long s = defaultGen.getAndAdd(GOLDEN_GAMMA << 1);
379 >        this.seed = mix64(s);
380 >        this.gamma = mixGamma(s + GOLDEN_GAMMA);
381      }
382  
383      /**
# Line 405 | Line 395 | public class SplittableRandom {
395       * @return the new SplittableRandom instance
396       */
397      public SplittableRandom split() {
398 <        long s = nextSeed();
409 <        return new SplittableRandom(s, nextGamma(s));
398 >        return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
399      }
400  
401      /**
# Line 429 | Line 418 | public class SplittableRandom {
418       */
419      public int nextInt(int bound) {
420          if (bound <= 0)
421 <            throw new IllegalArgumentException(BadBound);
421 >            throw new IllegalArgumentException(BAD_BOUND);
422          // Specialize internalNextInt for origin 0
423          int r = mix32(nextSeed());
424          int m = bound - 1;
# Line 457 | Line 446 | public class SplittableRandom {
446       */
447      public int nextInt(int origin, int bound) {
448          if (origin >= bound)
449 <            throw new IllegalArgumentException(BadRange);
449 >            throw new IllegalArgumentException(BAD_RANGE);
450          return internalNextInt(origin, bound);
451      }
452  
# Line 481 | Line 470 | public class SplittableRandom {
470       */
471      public long nextLong(long bound) {
472          if (bound <= 0)
473 <            throw new IllegalArgumentException(BadBound);
473 >            throw new IllegalArgumentException(BAD_BOUND);
474          // Specialize internalNextLong for origin 0
475          long r = mix64(nextSeed());
476          long m = bound - 1;
# Line 509 | Line 498 | public class SplittableRandom {
498       */
499      public long nextLong(long origin, long bound) {
500          if (origin >= bound)
501 <            throw new IllegalArgumentException(BadRange);
501 >            throw new IllegalArgumentException(BAD_RANGE);
502          return internalNextLong(origin, bound);
503      }
504  
# Line 535 | Line 524 | public class SplittableRandom {
524       */
525      public double nextDouble(double bound) {
526          if (!(bound > 0.0))
527 <            throw new IllegalArgumentException(BadBound);
527 >            throw new IllegalArgumentException(BAD_BOUND);
528          double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
529          return (result < bound) ?  result : // correct for rounding
530              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
# Line 554 | Line 543 | public class SplittableRandom {
543       */
544      public double nextDouble(double origin, double bound) {
545          if (!(origin < bound))
546 <            throw new IllegalArgumentException(BadRange);
546 >            throw new IllegalArgumentException(BAD_RANGE);
547          return internalNextDouble(origin, bound);
548      }
549  
# Line 582 | Line 571 | public class SplittableRandom {
571       */
572      public IntStream ints(long streamSize) {
573          if (streamSize < 0L)
574 <            throw new IllegalArgumentException(BadSize);
574 >            throw new IllegalArgumentException(BAD_SIZE);
575          return StreamSupport.intStream
576              (new RandomIntsSpliterator
577               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 623 | Line 612 | public class SplittableRandom {
612      public IntStream ints(long streamSize, int randomNumberOrigin,
613                            int randomNumberBound) {
614          if (streamSize < 0L)
615 <            throw new IllegalArgumentException(BadSize);
615 >            throw new IllegalArgumentException(BAD_SIZE);
616          if (randomNumberOrigin >= randomNumberBound)
617 <            throw new IllegalArgumentException(BadRange);
617 >            throw new IllegalArgumentException(BAD_RANGE);
618          return StreamSupport.intStream
619              (new RandomIntsSpliterator
620               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 649 | Line 638 | public class SplittableRandom {
638       */
639      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
640          if (randomNumberOrigin >= randomNumberBound)
641 <            throw new IllegalArgumentException(BadRange);
641 >            throw new IllegalArgumentException(BAD_RANGE);
642          return StreamSupport.intStream
643              (new RandomIntsSpliterator
644               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 668 | Line 657 | public class SplittableRandom {
657       */
658      public LongStream longs(long streamSize) {
659          if (streamSize < 0L)
660 <            throw new IllegalArgumentException(BadSize);
660 >            throw new IllegalArgumentException(BAD_SIZE);
661          return StreamSupport.longStream
662              (new RandomLongsSpliterator
663               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 709 | Line 698 | public class SplittableRandom {
698      public LongStream longs(long streamSize, long randomNumberOrigin,
699                              long randomNumberBound) {
700          if (streamSize < 0L)
701 <            throw new IllegalArgumentException(BadSize);
701 >            throw new IllegalArgumentException(BAD_SIZE);
702          if (randomNumberOrigin >= randomNumberBound)
703 <            throw new IllegalArgumentException(BadRange);
703 >            throw new IllegalArgumentException(BAD_RANGE);
704          return StreamSupport.longStream
705              (new RandomLongsSpliterator
706               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 735 | Line 724 | public class SplittableRandom {
724       */
725      public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
726          if (randomNumberOrigin >= randomNumberBound)
727 <            throw new IllegalArgumentException(BadRange);
727 >            throw new IllegalArgumentException(BAD_RANGE);
728          return StreamSupport.longStream
729              (new RandomLongsSpliterator
730               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 754 | Line 743 | public class SplittableRandom {
743       */
744      public DoubleStream doubles(long streamSize) {
745          if (streamSize < 0L)
746 <            throw new IllegalArgumentException(BadSize);
746 >            throw new IllegalArgumentException(BAD_SIZE);
747          return StreamSupport.doubleStream
748              (new RandomDoublesSpliterator
749               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 790 | Line 779 | public class SplittableRandom {
779       * @return a stream of pseudorandom {@code double} values,
780       *         each with the given origin (inclusive) and bound (exclusive)
781       * @throws IllegalArgumentException if {@code streamSize} is
782 <     *         less than zero
794 <     * @throws IllegalArgumentException if {@code randomNumberOrigin}
782 >     *         less than zero, or {@code randomNumberOrigin}
783       *         is greater than or equal to {@code randomNumberBound}
784       */
785      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
786                                  double randomNumberBound) {
787          if (streamSize < 0L)
788 <            throw new IllegalArgumentException(BadSize);
788 >            throw new IllegalArgumentException(BAD_SIZE);
789          if (!(randomNumberOrigin < randomNumberBound))
790 <            throw new IllegalArgumentException(BadRange);
790 >            throw new IllegalArgumentException(BAD_RANGE);
791          return StreamSupport.doubleStream
792              (new RandomDoublesSpliterator
793               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 823 | Line 811 | public class SplittableRandom {
811       */
812      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
813          if (!(randomNumberOrigin < randomNumberBound))
814 <            throw new IllegalArgumentException(BadRange);
814 >            throw new IllegalArgumentException(BAD_RANGE);
815          return StreamSupport.doubleStream
816              (new RandomDoublesSpliterator
817               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 838 | Line 826 | public class SplittableRandom {
826       * approach. The long and double versions of this class are
827       * identical except for types.
828       */
829 <    static final class RandomIntsSpliterator implements Spliterator.OfInt {
829 >    private static final class RandomIntsSpliterator
830 >            implements Spliterator.OfInt {
831          final SplittableRandom rng;
832          long index;
833          final long fence;
# Line 893 | Line 882 | public class SplittableRandom {
882      /**
883       * Spliterator for long streams.
884       */
885 <    static final class RandomLongsSpliterator implements Spliterator.OfLong {
885 >    private static final class RandomLongsSpliterator
886 >            implements Spliterator.OfLong {
887          final SplittableRandom rng;
888          long index;
889          final long fence;
# Line 949 | Line 939 | public class SplittableRandom {
939      /**
940       * Spliterator for double streams.
941       */
942 <    static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
942 >    private static final class RandomDoublesSpliterator
943 >            implements Spliterator.OfDouble {
944          final SplittableRandom rng;
945          long index;
946          final long fence;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines