1 /* 2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util; 27 28 import java.util.concurrent.atomic.AtomicLong; 29 import java.util.function.IntConsumer; 30 import java.util.function.LongConsumer; 31 import java.util.function.DoubleConsumer; 32 import java.util.stream.StreamSupport; 33 import java.util.stream.IntStream; 34 import java.util.stream.LongStream; 35 import java.util.stream.DoubleStream; 36 37 /** 38 * A generator of uniform pseudorandom values applicable for use in 39 * (among other contexts) isolated parallel computations that may 40 * generate subtasks. Class {@code SplittableRandom} supports methods for 41 * producing pseudorandom numbers of type {@code int}, {@code long}, 42 * and {@code double} with similar usages as for class 43 * {@link java.util.Random} but differs in the following ways: 44 * 45 * <ul> 46 * 47 * <li>Series of generated values pass the DieHarder suite testing 48 * independence and uniformity properties of random number generators. 49 * (Most recently validated with <a 50 * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version 51 * 3.31.1</a>.) These tests validate only the methods for certain 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> 56 * 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> 64 * 65 * <li>Instances of SplittableRandom are <em>not</em> thread-safe. 66 * They are designed to be split, not shared, across threads. For 67 * example, a {@link java.util.concurrent.ForkJoinTask 68 * fork/join-style} computation using random numbers might include a 69 * construction of the form {@code new 70 * Subtask(aSplittableRandom.split()).fork()}. 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> 75 * 76 * </ul> 77 * 78 * <p>Instances of {@code SplittableRandom} are not cryptographically 79 * secure. Consider instead using {@link java.security.SecureRandom} 80 * in security-sensitive applications. Additionally, 81 * default-constructed instances do not use a cryptographically random 82 * seed unless the {@linkplain System#getProperty system property} 83 * {@code java.util.secureRandomSeed} is set to {@code true}. 84 * 85 * @author Guy Steele 86 * @author Doug Lea 87 * @since 1.8 88 */ 89 public final class SplittableRandom { 90 91 /* 92 * Implementation Overview. 93 * 94 * This algorithm was inspired by the "DotMix" algorithm by 95 * Leiserson, Schardl, and Sukha "Deterministic Parallel 96 * Random-Number Generation for Dynamic-Multithreading Platforms", 97 * PPoPP 2012, as well as those in "Parallel random numbers: as 98 * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It 99 * differs mainly in simplifying and cheapening operations. 100 * 101 * The primary update step (method nextSeed()) is to add a 102 * constant ("gamma") to the current (64 bit) seed, forming a 103 * simple sequence. The seed and the gamma values for any two 104 * SplittableRandom instances are highly likely to be different. 105 * 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 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 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. 131 * 132 * The resulting generator thus transforms a sequence in which 133 * (typically) many bits change on each step, with an inexpensive 134 * mixer with good (but less than cryptographically secure) 135 * avalanching. 136 * 137 * The default (no-argument) constructor, in essence, invokes 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 149 * carrying around twice the state add more overhead than appears 150 * warranted for current usages. 151 * 152 * File organization: First the non-public methods that constitute 153 * the main algorithm, then the main public methods, followed by 154 * some custom spliterator classes needed for stream methods. 155 */ 156 157 /** 158 * The golden ratio scaled to 64bits, used as the initial gamma 159 * value for (unsplit) SplittableRandoms. 160 */ 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 = 0x1.0p-53; // 1.0 / (1L << 53); 168 169 /** 170 * The seed. Updated only via method nextSeed. 171 */ 172 private long seed; 173 174 /** 175 * The step value. 176 */ 177 private final long gamma; 178 179 /** 180 * Internal constructor used by all others except default constructor. 181 */ SplittableRandom(long seed, long gamma)182 private SplittableRandom(long seed, long gamma) { 183 this.seed = seed; 184 this.gamma = gamma; 185 } 186 187 /** 188 * Computes Stafford variant 13 of 64bit mix function. 189 */ mix64(long z)190 private static long mix64(long z) { 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 Stafford variant 4 mix64 function as int. 198 */ mix32(long z)199 private static int mix32(long z) { 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 */ mixGamma(long 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 /** 216 * Adds gamma to seed. 217 */ nextSeed()218 private long nextSeed() { 219 return seed += gamma; 220 } 221 222 /** 223 * The seed generator for default constructors. 224 */ 225 private static final AtomicLong defaultGen = new AtomicLong(initialSeed()); 226 initialSeed()227 private static long initialSeed() { 228 String pp = java.security.AccessController.doPrivileged( 229 new sun.security.action.GetPropertyAction( 230 "java.util.secureRandomSeed")); 231 if (pp != null && pp.equalsIgnoreCase("true")) { 232 byte[] seedBytes = java.security.SecureRandom.getSeed(8); 233 long s = (long)(seedBytes[0]) & 0xffL; 234 for (int i = 1; i < 8; ++i) 235 s = (s << 8) | ((long)(seedBytes[i]) & 0xffL); 236 return s; 237 } 238 return (mix64(System.currentTimeMillis()) ^ 239 mix64(System.nanoTime())); 240 } 241 242 // IllegalArgumentException messages 243 static final String BadBound = "bound must be positive"; 244 static final String BadRange = "bound must be greater than origin"; 245 static final String BadSize = "size must be non-negative"; 246 247 /* 248 * Internal versions of nextX methods used by streams, as well as 249 * the public nextX(origin, bound) methods. These exist mainly to 250 * avoid the need for multiple versions of stream spliterators 251 * across the different exported forms of streams. 252 */ 253 254 /** 255 * The form of nextLong used by LongStream Spliterators. If 256 * origin is greater than bound, acts as unbounded form of 257 * nextLong, else as bounded form. 258 * 259 * @param origin the least value, unless greater than bound 260 * @param bound the upper bound (exclusive), must not equal origin 261 * @return a pseudorandom value 262 */ internalNextLong(long origin, long bound)263 final long internalNextLong(long origin, long bound) { 264 /* 265 * Four Cases: 266 * 267 * 1. If the arguments indicate unbounded form, act as 268 * nextLong(). 269 * 270 * 2. If the range is an exact power of two, apply the 271 * associated bit mask. 272 * 273 * 3. If the range is positive, loop to avoid potential bias 274 * when the implicit nextLong() bound (2<sup>64</sup>) is not 275 * evenly divisible by the range. The loop rejects candidates 276 * computed from otherwise over-represented values. The 277 * expected number of iterations under an ideal generator 278 * varies from 1 to 2, depending on the bound. The loop itself 279 * takes an unlovable form. Because the first candidate is 280 * already available, we need a break-in-the-middle 281 * construction, which is concisely but cryptically performed 282 * within the while-condition of a body-less for loop. 283 * 284 * 4. Otherwise, the range cannot be represented as a positive 285 * long. The loop repeatedly generates unbounded longs until 286 * obtaining a candidate meeting constraints (with an expected 287 * number of iterations of less than two). 288 */ 289 290 long r = mix64(nextSeed()); 291 if (origin < bound) { 292 long n = bound - origin, m = n - 1; 293 if ((n & m) == 0L) // power of two 294 r = (r & m) + origin; 295 else if (n > 0L) { // reject over-represented candidates 296 for (long u = r >>> 1; // ensure nonnegative 297 u + m - (r = u % n) < 0L; // rejection check 298 u = mix64(nextSeed()) >>> 1) // retry 299 ; 300 r += origin; 301 } 302 else { // range not representable as long 303 while (r < origin || r >= bound) 304 r = mix64(nextSeed()); 305 } 306 } 307 return r; 308 } 309 310 /** 311 * The form of nextInt used by IntStream Spliterators. 312 * Exactly the same as long version, except for types. 313 * 314 * @param origin the least value, unless greater than bound 315 * @param bound the upper bound (exclusive), must not equal origin 316 * @return a pseudorandom value 317 */ internalNextInt(int origin, int bound)318 final int internalNextInt(int origin, int bound) { 319 int r = mix32(nextSeed()); 320 if (origin < bound) { 321 int n = bound - origin, m = n - 1; 322 if ((n & m) == 0) 323 r = (r & m) + origin; 324 else if (n > 0) { 325 for (int u = r >>> 1; 326 u + m - (r = u % n) < 0; 327 u = mix32(nextSeed()) >>> 1) 328 ; 329 r += origin; 330 } 331 else { 332 while (r < origin || r >= bound) 333 r = mix32(nextSeed()); 334 } 335 } 336 return r; 337 } 338 339 /** 340 * The form of nextDouble used by DoubleStream Spliterators. 341 * 342 * @param origin the least value, unless greater than bound 343 * @param bound the upper bound (exclusive), must not equal origin 344 * @return a pseudorandom value 345 */ internalNextDouble(double origin, double bound)346 final double internalNextDouble(double origin, double bound) { 347 double r = (nextLong() >>> 11) * DOUBLE_UNIT; 348 if (origin < bound) { 349 r = r * (bound - origin) + origin; 350 if (r >= bound) // correct for rounding 351 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); 352 } 353 return r; 354 } 355 356 /* ---------------- public methods ---------------- */ 357 358 /** 359 * Creates a new SplittableRandom instance using the specified 360 * initial seed. SplittableRandom instances created with the same 361 * seed in the same program generate identical sequences of values. 362 * 363 * @param seed the initial seed 364 */ SplittableRandom(long seed)365 public SplittableRandom(long seed) { 366 this(seed, GOLDEN_GAMMA); 367 } 368 369 /** 370 * Creates a new SplittableRandom instance that is likely to 371 * generate sequences of values that are statistically independent 372 * of those of any other instances in the current program; and 373 * may, and typically does, vary across program invocations. 374 */ SplittableRandom()375 public SplittableRandom() { // emulate defaultGen.split() 376 long s = defaultGen.getAndAdd(2 * GOLDEN_GAMMA); 377 this.seed = mix64(s); 378 this.gamma = mixGamma(s + GOLDEN_GAMMA); 379 } 380 381 /** 382 * Constructs and returns a new SplittableRandom instance that 383 * shares no mutable state with this instance. However, with very 384 * high probability, the set of values collectively generated by 385 * the two objects has the same statistical properties as if the 386 * same quantity of values were generated by a single thread using 387 * a single SplittableRandom object. Either or both of the two 388 * objects may be further split using the {@code split()} method, 389 * and the same expected statistical properties apply to the 390 * entire set of generators constructed by such recursive 391 * splitting. 392 * 393 * @return the new SplittableRandom instance 394 */ split()395 public SplittableRandom split() { 396 return new SplittableRandom(nextLong(), mixGamma(nextSeed())); 397 } 398 399 /** 400 * Returns a pseudorandom {@code int} value. 401 * 402 * @return a pseudorandom {@code int} value 403 */ nextInt()404 public int nextInt() { 405 return mix32(nextSeed()); 406 } 407 408 /** 409 * Returns a pseudorandom {@code int} value between zero (inclusive) 410 * and the specified bound (exclusive). 411 * 412 * @param bound the upper bound (exclusive). Must be positive. 413 * @return a pseudorandom {@code int} value between zero 414 * (inclusive) and the bound (exclusive) 415 * @throws IllegalArgumentException if {@code bound} is not positive 416 */ nextInt(int bound)417 public int nextInt(int bound) { 418 if (bound <= 0) 419 throw new IllegalArgumentException(BadBound); 420 // Specialize internalNextInt for origin 0 421 int r = mix32(nextSeed()); 422 int m = bound - 1; 423 if ((bound & m) == 0) // power of two 424 r &= m; 425 else { // reject over-represented candidates 426 for (int u = r >>> 1; 427 u + m - (r = u % bound) < 0; 428 u = mix32(nextSeed()) >>> 1) 429 ; 430 } 431 return r; 432 } 433 434 /** 435 * Returns a pseudorandom {@code int} value between the specified 436 * origin (inclusive) and the specified bound (exclusive). 437 * 438 * @param origin the least value returned 439 * @param bound the upper bound (exclusive) 440 * @return a pseudorandom {@code int} value between the origin 441 * (inclusive) and the bound (exclusive) 442 * @throws IllegalArgumentException if {@code origin} is greater than 443 * or equal to {@code bound} 444 */ nextInt(int origin, int bound)445 public int nextInt(int origin, int bound) { 446 if (origin >= bound) 447 throw new IllegalArgumentException(BadRange); 448 return internalNextInt(origin, bound); 449 } 450 451 /** 452 * Returns a pseudorandom {@code long} value. 453 * 454 * @return a pseudorandom {@code long} value 455 */ nextLong()456 public long nextLong() { 457 return mix64(nextSeed()); 458 } 459 460 /** 461 * Returns a pseudorandom {@code long} value between zero (inclusive) 462 * and the specified bound (exclusive). 463 * 464 * @param bound the upper bound (exclusive). Must be positive. 465 * @return a pseudorandom {@code long} value between zero 466 * (inclusive) and the bound (exclusive) 467 * @throws IllegalArgumentException if {@code bound} is not positive 468 */ nextLong(long bound)469 public long nextLong(long bound) { 470 if (bound <= 0) 471 throw new IllegalArgumentException(BadBound); 472 // Specialize internalNextLong for origin 0 473 long r = mix64(nextSeed()); 474 long m = bound - 1; 475 if ((bound & m) == 0L) // power of two 476 r &= m; 477 else { // reject over-represented candidates 478 for (long u = r >>> 1; 479 u + m - (r = u % bound) < 0L; 480 u = mix64(nextSeed()) >>> 1) 481 ; 482 } 483 return r; 484 } 485 486 /** 487 * Returns a pseudorandom {@code long} value between the specified 488 * origin (inclusive) and the specified bound (exclusive). 489 * 490 * @param origin the least value returned 491 * @param bound the upper bound (exclusive) 492 * @return a pseudorandom {@code long} value between the origin 493 * (inclusive) and the bound (exclusive) 494 * @throws IllegalArgumentException if {@code origin} is greater than 495 * or equal to {@code bound} 496 */ nextLong(long origin, long bound)497 public long nextLong(long origin, long bound) { 498 if (origin >= bound) 499 throw new IllegalArgumentException(BadRange); 500 return internalNextLong(origin, bound); 501 } 502 503 /** 504 * Returns a pseudorandom {@code double} value between zero 505 * (inclusive) and one (exclusive). 506 * 507 * @return a pseudorandom {@code double} value between zero 508 * (inclusive) and one (exclusive) 509 */ nextDouble()510 public double nextDouble() { 511 return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT; 512 } 513 514 /** 515 * Returns a pseudorandom {@code double} value between 0.0 516 * (inclusive) and the specified bound (exclusive). 517 * 518 * @param bound the upper bound (exclusive). Must be positive. 519 * @return a pseudorandom {@code double} value between zero 520 * (inclusive) and the bound (exclusive) 521 * @throws IllegalArgumentException if {@code bound} is not positive 522 */ nextDouble(double bound)523 public double nextDouble(double bound) { 524 if (!(bound > 0.0)) 525 throw new IllegalArgumentException(BadBound); 526 double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound; 527 return (result < bound) ? result : // correct for rounding 528 Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); 529 } 530 531 /** 532 * Returns a pseudorandom {@code double} value between the specified 533 * origin (inclusive) and bound (exclusive). 534 * 535 * @param origin the least value returned 536 * @param bound the upper bound (exclusive) 537 * @return a pseudorandom {@code double} value between the origin 538 * (inclusive) and the bound (exclusive) 539 * @throws IllegalArgumentException if {@code origin} is greater than 540 * or equal to {@code bound} 541 */ nextDouble(double origin, double bound)542 public double nextDouble(double origin, double bound) { 543 if (!(origin < bound)) 544 throw new IllegalArgumentException(BadRange); 545 return internalNextDouble(origin, bound); 546 } 547 548 /** 549 * Returns a pseudorandom {@code boolean} value. 550 * 551 * @return a pseudorandom {@code boolean} value 552 */ nextBoolean()553 public boolean nextBoolean() { 554 return mix32(nextSeed()) < 0; 555 } 556 557 // stream methods, coded in a way intended to better isolate for 558 // maintenance purposes the small differences across forms. 559 560 /** 561 * Returns a stream producing the given {@code streamSize} number 562 * of pseudorandom {@code int} values from this generator and/or 563 * one split from it. 564 * 565 * @param streamSize the number of values to generate 566 * @return a stream of pseudorandom {@code int} values 567 * @throws IllegalArgumentException if {@code streamSize} is 568 * less than zero 569 */ ints(long streamSize)570 public IntStream ints(long streamSize) { 571 if (streamSize < 0L) 572 throw new IllegalArgumentException(BadSize); 573 return StreamSupport.intStream 574 (new RandomIntsSpliterator 575 (this, 0L, streamSize, Integer.MAX_VALUE, 0), 576 false); 577 } 578 579 /** 580 * Returns an effectively unlimited stream of pseudorandom {@code int} 581 * values from this generator and/or one split from it. 582 * 583 * @implNote This method is implemented to be equivalent to {@code 584 * ints(Long.MAX_VALUE)}. 585 * 586 * @return a stream of pseudorandom {@code int} values 587 */ ints()588 public IntStream ints() { 589 return StreamSupport.intStream 590 (new RandomIntsSpliterator 591 (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), 592 false); 593 } 594 595 /** 596 * Returns a stream producing the given {@code streamSize} number 597 * of pseudorandom {@code int} values from this generator and/or one split 598 * from it; each value conforms to the given origin (inclusive) and bound 599 * (exclusive). 600 * 601 * @param streamSize the number of values to generate 602 * @param randomNumberOrigin the origin (inclusive) of each random value 603 * @param randomNumberBound the bound (exclusive) of each random value 604 * @return a stream of pseudorandom {@code int} values, 605 * each with the given origin (inclusive) and bound (exclusive) 606 * @throws IllegalArgumentException if {@code streamSize} is 607 * less than zero, or {@code randomNumberOrigin} 608 * is greater than or equal to {@code randomNumberBound} 609 */ ints(long streamSize, int randomNumberOrigin, int randomNumberBound)610 public IntStream ints(long streamSize, int randomNumberOrigin, 611 int randomNumberBound) { 612 if (streamSize < 0L) 613 throw new IllegalArgumentException(BadSize); 614 if (randomNumberOrigin >= randomNumberBound) 615 throw new IllegalArgumentException(BadRange); 616 return StreamSupport.intStream 617 (new RandomIntsSpliterator 618 (this, 0L, streamSize, randomNumberOrigin, randomNumberBound), 619 false); 620 } 621 622 /** 623 * Returns an effectively unlimited stream of pseudorandom {@code 624 * int} values from this generator and/or one split from it; each value 625 * conforms to the given origin (inclusive) and bound (exclusive). 626 * 627 * @implNote This method is implemented to be equivalent to {@code 628 * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. 629 * 630 * @param randomNumberOrigin the origin (inclusive) of each random value 631 * @param randomNumberBound the bound (exclusive) of each random value 632 * @return a stream of pseudorandom {@code int} values, 633 * each with the given origin (inclusive) and bound (exclusive) 634 * @throws IllegalArgumentException if {@code randomNumberOrigin} 635 * is greater than or equal to {@code randomNumberBound} 636 */ ints(int randomNumberOrigin, int randomNumberBound)637 public IntStream ints(int randomNumberOrigin, int randomNumberBound) { 638 if (randomNumberOrigin >= randomNumberBound) 639 throw new IllegalArgumentException(BadRange); 640 return StreamSupport.intStream 641 (new RandomIntsSpliterator 642 (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), 643 false); 644 } 645 646 /** 647 * Returns a stream producing the given {@code streamSize} number 648 * of pseudorandom {@code long} values from this generator and/or 649 * one split from it. 650 * 651 * @param streamSize the number of values to generate 652 * @return a stream of pseudorandom {@code long} values 653 * @throws IllegalArgumentException if {@code streamSize} is 654 * less than zero 655 */ longs(long streamSize)656 public LongStream longs(long streamSize) { 657 if (streamSize < 0L) 658 throw new IllegalArgumentException(BadSize); 659 return StreamSupport.longStream 660 (new RandomLongsSpliterator 661 (this, 0L, streamSize, Long.MAX_VALUE, 0L), 662 false); 663 } 664 665 /** 666 * Returns an effectively unlimited stream of pseudorandom {@code 667 * long} values from this generator and/or one split from it. 668 * 669 * @implNote This method is implemented to be equivalent to {@code 670 * longs(Long.MAX_VALUE)}. 671 * 672 * @return a stream of pseudorandom {@code long} values 673 */ longs()674 public LongStream longs() { 675 return StreamSupport.longStream 676 (new RandomLongsSpliterator 677 (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), 678 false); 679 } 680 681 /** 682 * Returns a stream producing the given {@code streamSize} number of 683 * pseudorandom {@code long} values from this generator and/or one split 684 * from it; each value conforms to the given origin (inclusive) and bound 685 * (exclusive). 686 * 687 * @param streamSize the number of values to generate 688 * @param randomNumberOrigin the origin (inclusive) of each random value 689 * @param randomNumberBound the bound (exclusive) of each random value 690 * @return a stream of pseudorandom {@code long} values, 691 * each with the given origin (inclusive) and bound (exclusive) 692 * @throws IllegalArgumentException if {@code streamSize} is 693 * less than zero, or {@code randomNumberOrigin} 694 * is greater than or equal to {@code randomNumberBound} 695 */ longs(long streamSize, long randomNumberOrigin, long randomNumberBound)696 public LongStream longs(long streamSize, long randomNumberOrigin, 697 long randomNumberBound) { 698 if (streamSize < 0L) 699 throw new IllegalArgumentException(BadSize); 700 if (randomNumberOrigin >= randomNumberBound) 701 throw new IllegalArgumentException(BadRange); 702 return StreamSupport.longStream 703 (new RandomLongsSpliterator 704 (this, 0L, streamSize, randomNumberOrigin, randomNumberBound), 705 false); 706 } 707 708 /** 709 * Returns an effectively unlimited stream of pseudorandom {@code 710 * long} values from this generator and/or one split from it; each value 711 * conforms to the given origin (inclusive) and bound (exclusive). 712 * 713 * @implNote This method is implemented to be equivalent to {@code 714 * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. 715 * 716 * @param randomNumberOrigin the origin (inclusive) of each random value 717 * @param randomNumberBound the bound (exclusive) of each random value 718 * @return a stream of pseudorandom {@code long} values, 719 * each with the given origin (inclusive) and bound (exclusive) 720 * @throws IllegalArgumentException if {@code randomNumberOrigin} 721 * is greater than or equal to {@code randomNumberBound} 722 */ longs(long randomNumberOrigin, long randomNumberBound)723 public LongStream longs(long randomNumberOrigin, long randomNumberBound) { 724 if (randomNumberOrigin >= randomNumberBound) 725 throw new IllegalArgumentException(BadRange); 726 return StreamSupport.longStream 727 (new RandomLongsSpliterator 728 (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), 729 false); 730 } 731 732 /** 733 * Returns a stream producing the given {@code streamSize} number of 734 * pseudorandom {@code double} values from this generator and/or one split 735 * from it; each value is between zero (inclusive) and one (exclusive). 736 * 737 * @param streamSize the number of values to generate 738 * @return a stream of {@code double} values 739 * @throws IllegalArgumentException if {@code streamSize} is 740 * less than zero 741 */ doubles(long streamSize)742 public DoubleStream doubles(long streamSize) { 743 if (streamSize < 0L) 744 throw new IllegalArgumentException(BadSize); 745 return StreamSupport.doubleStream 746 (new RandomDoublesSpliterator 747 (this, 0L, streamSize, Double.MAX_VALUE, 0.0), 748 false); 749 } 750 751 /** 752 * Returns an effectively unlimited stream of pseudorandom {@code 753 * double} values from this generator and/or one split from it; each value 754 * is between zero (inclusive) and one (exclusive). 755 * 756 * @implNote This method is implemented to be equivalent to {@code 757 * doubles(Long.MAX_VALUE)}. 758 * 759 * @return a stream of pseudorandom {@code double} values 760 */ doubles()761 public DoubleStream doubles() { 762 return StreamSupport.doubleStream 763 (new RandomDoublesSpliterator 764 (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), 765 false); 766 } 767 768 /** 769 * Returns a stream producing the given {@code streamSize} number of 770 * pseudorandom {@code double} values from this generator and/or one split 771 * from it; each value conforms to the given origin (inclusive) and bound 772 * (exclusive). 773 * 774 * @param streamSize the number of values to generate 775 * @param randomNumberOrigin the origin (inclusive) of each random value 776 * @param randomNumberBound the bound (exclusive) of each random value 777 * @return a stream of pseudorandom {@code double} values, 778 * each with the given origin (inclusive) and bound (exclusive) 779 * @throws IllegalArgumentException if {@code streamSize} is 780 * less than zero 781 * @throws IllegalArgumentException if {@code randomNumberOrigin} 782 * is greater than or equal to {@code randomNumberBound} 783 */ doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)784 public DoubleStream doubles(long streamSize, double randomNumberOrigin, 785 double randomNumberBound) { 786 if (streamSize < 0L) 787 throw new IllegalArgumentException(BadSize); 788 if (!(randomNumberOrigin < randomNumberBound)) 789 throw new IllegalArgumentException(BadRange); 790 return StreamSupport.doubleStream 791 (new RandomDoublesSpliterator 792 (this, 0L, streamSize, randomNumberOrigin, randomNumberBound), 793 false); 794 } 795 796 /** 797 * Returns an effectively unlimited stream of pseudorandom {@code 798 * double} values from this generator and/or one split from it; each value 799 * conforms to the given origin (inclusive) and bound (exclusive). 800 * 801 * @implNote This method is implemented to be equivalent to {@code 802 * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. 803 * 804 * @param randomNumberOrigin the origin (inclusive) of each random value 805 * @param randomNumberBound the bound (exclusive) of each random value 806 * @return a stream of pseudorandom {@code double} values, 807 * each with the given origin (inclusive) and bound (exclusive) 808 * @throws IllegalArgumentException if {@code randomNumberOrigin} 809 * is greater than or equal to {@code randomNumberBound} 810 */ doubles(double randomNumberOrigin, double randomNumberBound)811 public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { 812 if (!(randomNumberOrigin < randomNumberBound)) 813 throw new IllegalArgumentException(BadRange); 814 return StreamSupport.doubleStream 815 (new RandomDoublesSpliterator 816 (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), 817 false); 818 } 819 820 /** 821 * Spliterator for int streams. We multiplex the four int 822 * versions into one class by treating a bound less than origin as 823 * unbounded, and also by treating "infinite" as equivalent to 824 * Long.MAX_VALUE. For splits, it uses the standard divide-by-two 825 * approach. The long and double versions of this class are 826 * identical except for types. 827 */ 828 static final class RandomIntsSpliterator implements Spliterator.OfInt { 829 final SplittableRandom rng; 830 long index; 831 final long fence; 832 final int origin; 833 final int bound; RandomIntsSpliterator(SplittableRandom rng, long index, long fence, int origin, int bound)834 RandomIntsSpliterator(SplittableRandom rng, long index, long fence, 835 int origin, int bound) { 836 this.rng = rng; this.index = index; this.fence = fence; 837 this.origin = origin; this.bound = bound; 838 } 839 trySplit()840 public RandomIntsSpliterator trySplit() { 841 long i = index, m = (i + fence) >>> 1; 842 return (m <= i) ? null : 843 new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound); 844 } 845 estimateSize()846 public long estimateSize() { 847 return fence - index; 848 } 849 characteristics()850 public int characteristics() { 851 return (Spliterator.SIZED | Spliterator.SUBSIZED | 852 Spliterator.NONNULL | Spliterator.IMMUTABLE); 853 } 854 tryAdvance(IntConsumer consumer)855 public boolean tryAdvance(IntConsumer consumer) { 856 if (consumer == null) throw new NullPointerException(); 857 long i = index, f = fence; 858 if (i < f) { 859 consumer.accept(rng.internalNextInt(origin, bound)); 860 index = i + 1; 861 return true; 862 } 863 return false; 864 } 865 forEachRemaining(IntConsumer consumer)866 public void forEachRemaining(IntConsumer consumer) { 867 if (consumer == null) throw new NullPointerException(); 868 long i = index, f = fence; 869 if (i < f) { 870 index = f; 871 SplittableRandom r = rng; 872 int o = origin, b = bound; 873 do { 874 consumer.accept(r.internalNextInt(o, b)); 875 } while (++i < f); 876 } 877 } 878 } 879 880 /** 881 * Spliterator for long streams. 882 */ 883 static final class RandomLongsSpliterator implements Spliterator.OfLong { 884 final SplittableRandom rng; 885 long index; 886 final long fence; 887 final long origin; 888 final long bound; RandomLongsSpliterator(SplittableRandom rng, long index, long fence, long origin, long bound)889 RandomLongsSpliterator(SplittableRandom rng, long index, long fence, 890 long origin, long bound) { 891 this.rng = rng; this.index = index; this.fence = fence; 892 this.origin = origin; this.bound = bound; 893 } 894 trySplit()895 public RandomLongsSpliterator trySplit() { 896 long i = index, m = (i + fence) >>> 1; 897 return (m <= i) ? null : 898 new RandomLongsSpliterator(rng.split(), i, index = m, origin, bound); 899 } 900 estimateSize()901 public long estimateSize() { 902 return fence - index; 903 } 904 characteristics()905 public int characteristics() { 906 return (Spliterator.SIZED | Spliterator.SUBSIZED | 907 Spliterator.NONNULL | Spliterator.IMMUTABLE); 908 } 909 tryAdvance(LongConsumer consumer)910 public boolean tryAdvance(LongConsumer consumer) { 911 if (consumer == null) throw new NullPointerException(); 912 long i = index, f = fence; 913 if (i < f) { 914 consumer.accept(rng.internalNextLong(origin, bound)); 915 index = i + 1; 916 return true; 917 } 918 return false; 919 } 920 forEachRemaining(LongConsumer consumer)921 public void forEachRemaining(LongConsumer consumer) { 922 if (consumer == null) throw new NullPointerException(); 923 long i = index, f = fence; 924 if (i < f) { 925 index = f; 926 SplittableRandom r = rng; 927 long o = origin, b = bound; 928 do { 929 consumer.accept(r.internalNextLong(o, b)); 930 } while (++i < f); 931 } 932 } 933 934 } 935 936 /** 937 * Spliterator for double streams. 938 */ 939 static final class RandomDoublesSpliterator implements Spliterator.OfDouble { 940 final SplittableRandom rng; 941 long index; 942 final long fence; 943 final double origin; 944 final double bound; RandomDoublesSpliterator(SplittableRandom rng, long index, long fence, double origin, double bound)945 RandomDoublesSpliterator(SplittableRandom rng, long index, long fence, 946 double origin, double bound) { 947 this.rng = rng; this.index = index; this.fence = fence; 948 this.origin = origin; this.bound = bound; 949 } 950 trySplit()951 public RandomDoublesSpliterator trySplit() { 952 long i = index, m = (i + fence) >>> 1; 953 return (m <= i) ? null : 954 new RandomDoublesSpliterator(rng.split(), i, index = m, origin, bound); 955 } 956 estimateSize()957 public long estimateSize() { 958 return fence - index; 959 } 960 characteristics()961 public int characteristics() { 962 return (Spliterator.SIZED | Spliterator.SUBSIZED | 963 Spliterator.NONNULL | Spliterator.IMMUTABLE); 964 } 965 tryAdvance(DoubleConsumer consumer)966 public boolean tryAdvance(DoubleConsumer consumer) { 967 if (consumer == null) throw new NullPointerException(); 968 long i = index, f = fence; 969 if (i < f) { 970 consumer.accept(rng.internalNextDouble(origin, bound)); 971 index = i + 1; 972 return true; 973 } 974 return false; 975 } 976 forEachRemaining(DoubleConsumer consumer)977 public void forEachRemaining(DoubleConsumer consumer) { 978 if (consumer == null) throw new NullPointerException(); 979 long i = index, f = fence; 980 if (i < f) { 981 index = f; 982 SplittableRandom r = rng; 983 double o = origin, b = bound; 984 do { 985 consumer.accept(r.internalNextDouble(o, b)); 986 } while (++i < f); 987 } 988 } 989 } 990 991 } 992