ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.40
Committed: Fri Feb 19 03:39:15 2016 UTC (8 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.39: +5 -3 lines
Log Message:
unlambdafy to "fix" 8150014: java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java fails with NoClassDefFoundError

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.io.ObjectStreamField;
10 import java.util.Random;
11 import java.util.Spliterator;
12 import java.util.concurrent.atomic.AtomicInteger;
13 import java.util.concurrent.atomic.AtomicLong;
14 import java.util.function.DoubleConsumer;
15 import java.util.function.IntConsumer;
16 import java.util.function.LongConsumer;
17 import java.util.stream.DoubleStream;
18 import java.util.stream.IntStream;
19 import java.util.stream.LongStream;
20 import java.util.stream.StreamSupport;
21
22 /**
23 * A random number generator isolated to the current thread. Like the
24 * global {@link java.util.Random} generator used by the {@link
25 * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
26 * with an internally generated seed that may not otherwise be
27 * modified. When applicable, use of {@code ThreadLocalRandom} rather
28 * than shared {@code Random} objects in concurrent programs will
29 * typically encounter much less overhead and contention. Use of
30 * {@code ThreadLocalRandom} is particularly appropriate when multiple
31 * tasks (for example, each a {@link ForkJoinTask}) use random numbers
32 * in parallel in thread pools.
33 *
34 * <p>Usages of this class should typically be of the form:
35 * {@code ThreadLocalRandom.current().nextX(...)} (where
36 * {@code X} is {@code Int}, {@code Long}, etc).
37 * When all usages are of this form, it is never possible to
38 * accidently share a {@code ThreadLocalRandom} across multiple threads.
39 *
40 * <p>This class also provides additional commonly used bounded random
41 * generation methods.
42 *
43 * <p>Instances of {@code ThreadLocalRandom} are not cryptographically
44 * secure. Consider instead using {@link java.security.SecureRandom}
45 * in security-sensitive applications. Additionally,
46 * default-constructed instances do not use a cryptographically random
47 * seed unless the {@linkplain System#getProperty system property}
48 * {@code java.util.secureRandomSeed} is set to {@code true}.
49 *
50 * @since 1.7
51 * @author Doug Lea
52 */
53 public class ThreadLocalRandom extends Random {
54 /*
55 * This class implements the java.util.Random API (and subclasses
56 * Random) using a single static instance that accesses random
57 * number state held in class Thread (primarily, field
58 * threadLocalRandomSeed). In doing so, it also provides a home
59 * for managing package-private utilities that rely on exactly the
60 * same state as needed to maintain the ThreadLocalRandom
61 * instances. We leverage the need for an initialization flag
62 * field to also use it as a "probe" -- a self-adjusting thread
63 * hash used for contention avoidance, as well as a secondary
64 * simpler (xorShift) random seed that is conservatively used to
65 * avoid otherwise surprising users by hijacking the
66 * ThreadLocalRandom sequence. The dual use is a marriage of
67 * convenience, but is a simple and efficient way of reducing
68 * application-level overhead and footprint of most concurrent
69 * programs.
70 *
71 * Even though this class subclasses java.util.Random, it uses the
72 * same basic algorithm as java.util.SplittableRandom. (See its
73 * internal documentation for explanations, which are not repeated
74 * here.) Because ThreadLocalRandoms are not splittable
75 * though, we use only a single 64bit gamma.
76 *
77 * Because this class is in a different package than class Thread,
78 * field access methods use Unsafe to bypass access control rules.
79 * To conform to the requirements of the Random superclass
80 * constructor, the common static ThreadLocalRandom maintains an
81 * "initialized" field for the sake of rejecting user calls to
82 * setSeed while still allowing a call from constructor. Note
83 * that serialization is completely unnecessary because there is
84 * only a static singleton. But we generate a serial form
85 * containing "rnd" and "initialized" fields to ensure
86 * compatibility across versions.
87 *
88 * Implementations of non-core methods are mostly the same as in
89 * SplittableRandom, that were in part derived from a previous
90 * version of this class.
91 *
92 * The nextLocalGaussian ThreadLocal supports the very rarely used
93 * nextGaussian method by providing a holder for the second of a
94 * pair of them. As is true for the base class version of this
95 * method, this time/space tradeoff is probably never worthwhile,
96 * but we provide identical statistical properties.
97 */
98
99 /** Generates per-thread initialization/probe field */
100 private static final AtomicInteger probeGenerator = new AtomicInteger();
101
102 /**
103 * The next seed for default constructors.
104 */
105 private static final AtomicLong seeder = new AtomicLong(initialSeed());
106
107 private static long initialSeed() {
108 if (java.security.AccessController.doPrivileged(
109 new java.security.PrivilegedAction<Boolean>() {
110 public Boolean run() {
111 return Boolean.getBoolean("java.util.secureRandomSeed");
112 }})) {
113 byte[] seedBytes = java.security.SecureRandom.getSeed(8);
114 long s = (long)seedBytes[0] & 0xffL;
115 for (int i = 1; i < 8; ++i)
116 s = (s << 8) | ((long)seedBytes[i] & 0xffL);
117 return s;
118 }
119 return (mix64(System.currentTimeMillis()) ^
120 mix64(System.nanoTime()));
121 }
122
123 /**
124 * The seed increment.
125 */
126 private static final long GAMMA = 0x9e3779b97f4a7c15L;
127
128 /**
129 * The increment for generating probe values.
130 */
131 private static final int PROBE_INCREMENT = 0x9e3779b9;
132
133 /**
134 * The increment of seeder per new instance.
135 */
136 private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
137
138 // Constants from SplittableRandom
139 private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
140 private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
141
142 /** Rarely-used holder for the second of a pair of Gaussians */
143 private static final ThreadLocal<Double> nextLocalGaussian =
144 new ThreadLocal<>();
145
146 private static long mix64(long z) {
147 z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
148 z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
149 return z ^ (z >>> 33);
150 }
151
152 private static int mix32(long z) {
153 z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
154 return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
155 }
156
157 /**
158 * Field used only during singleton initialization.
159 * True when constructor completes.
160 */
161 boolean initialized;
162
163 /** Constructor used only for static singleton */
164 private ThreadLocalRandom() {
165 initialized = true; // false during super() call
166 }
167
168 /** The common ThreadLocalRandom */
169 static final ThreadLocalRandom instance = new ThreadLocalRandom();
170
171 /**
172 * Initialize Thread fields for the current thread. Called only
173 * when Thread.threadLocalRandomProbe is zero, indicating that a
174 * thread local seed value needs to be generated. Note that even
175 * though the initialization is purely thread-local, we need to
176 * rely on (static) atomic generators to initialize the values.
177 */
178 static final void localInit() {
179 int p = probeGenerator.addAndGet(PROBE_INCREMENT);
180 int probe = (p == 0) ? 1 : p; // skip 0
181 long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
182 Thread t = Thread.currentThread();
183 U.putLong(t, SEED, seed);
184 U.putInt(t, PROBE, probe);
185 }
186
187 /**
188 * Returns the current thread's {@code ThreadLocalRandom}.
189 *
190 * @return the current thread's {@code ThreadLocalRandom}
191 */
192 public static ThreadLocalRandom current() {
193 if (U.getInt(Thread.currentThread(), PROBE) == 0)
194 localInit();
195 return instance;
196 }
197
198 /**
199 * Throws {@code UnsupportedOperationException}. Setting seeds in
200 * this generator is not supported.
201 *
202 * @throws UnsupportedOperationException always
203 */
204 public void setSeed(long seed) {
205 // only allow call from super() constructor
206 if (initialized)
207 throw new UnsupportedOperationException();
208 }
209
210 final long nextSeed() {
211 Thread t; long r; // read and update per-thread seed
212 U.putLong(t = Thread.currentThread(), SEED,
213 r = U.getLong(t, SEED) + GAMMA);
214 return r;
215 }
216
217 // We must define this, but never use it.
218 protected int next(int bits) {
219 return (int)(mix64(nextSeed()) >>> (64 - bits));
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 form of nextLong used by LongStream Spliterators. If
229 * origin is greater than bound, acts as unbounded form of
230 * nextLong, else as bounded form.
231 *
232 * @param origin the least value, unless greater than bound
233 * @param bound the upper bound (exclusive), must not equal origin
234 * @return a pseudorandom value
235 */
236 final long internalNextLong(long origin, long bound) {
237 long r = mix64(nextSeed());
238 if (origin < bound) {
239 long n = bound - origin, m = n - 1;
240 if ((n & m) == 0L) // power of two
241 r = (r & m) + origin;
242 else if (n > 0L) { // reject over-represented candidates
243 for (long u = r >>> 1; // ensure nonnegative
244 u + m - (r = u % n) < 0L; // rejection check
245 u = mix64(nextSeed()) >>> 1) // retry
246 ;
247 r += origin;
248 }
249 else { // range not representable as long
250 while (r < origin || r >= bound)
251 r = mix64(nextSeed());
252 }
253 }
254 return r;
255 }
256
257 /**
258 * The form of nextInt used by IntStream Spliterators.
259 * Exactly the same as long version, except for types.
260 *
261 * @param origin the least value, unless greater than bound
262 * @param bound the upper bound (exclusive), must not equal origin
263 * @return a pseudorandom value
264 */
265 final int internalNextInt(int origin, int bound) {
266 int r = mix32(nextSeed());
267 if (origin < bound) {
268 int n = bound - origin, m = n - 1;
269 if ((n & m) == 0)
270 r = (r & m) + origin;
271 else if (n > 0) {
272 for (int u = r >>> 1;
273 u + m - (r = u % n) < 0;
274 u = mix32(nextSeed()) >>> 1)
275 ;
276 r += origin;
277 }
278 else {
279 while (r < origin || r >= bound)
280 r = mix32(nextSeed());
281 }
282 }
283 return r;
284 }
285
286 /**
287 * The form of nextDouble used by DoubleStream Spliterators.
288 *
289 * @param origin the least value, unless greater than bound
290 * @param bound the upper bound (exclusive), must not equal origin
291 * @return a pseudorandom value
292 */
293 final double internalNextDouble(double origin, double bound) {
294 double r = (nextLong() >>> 11) * DOUBLE_UNIT;
295 if (origin < bound) {
296 r = r * (bound - origin) + origin;
297 if (r >= bound) // correct for rounding
298 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
299 }
300 return r;
301 }
302
303 /**
304 * Returns a pseudorandom {@code int} value.
305 *
306 * @return a pseudorandom {@code int} value
307 */
308 public int nextInt() {
309 return mix32(nextSeed());
310 }
311
312 /**
313 * Returns a pseudorandom {@code int} value between zero (inclusive)
314 * and the specified bound (exclusive).
315 *
316 * @param bound the upper bound (exclusive). Must be positive.
317 * @return a pseudorandom {@code int} value between zero
318 * (inclusive) and the bound (exclusive)
319 * @throws IllegalArgumentException if {@code bound} is not positive
320 */
321 public int nextInt(int bound) {
322 if (bound <= 0)
323 throw new IllegalArgumentException(BAD_BOUND);
324 int r = mix32(nextSeed());
325 int m = bound - 1;
326 if ((bound & m) == 0) // power of two
327 r &= m;
328 else { // reject over-represented candidates
329 for (int u = r >>> 1;
330 u + m - (r = u % bound) < 0;
331 u = mix32(nextSeed()) >>> 1)
332 ;
333 }
334 return r;
335 }
336
337 /**
338 * Returns a pseudorandom {@code int} value between the specified
339 * origin (inclusive) and the specified bound (exclusive).
340 *
341 * @param origin the least value returned
342 * @param bound the upper bound (exclusive)
343 * @return a pseudorandom {@code int} value between the origin
344 * (inclusive) and the bound (exclusive)
345 * @throws IllegalArgumentException if {@code origin} is greater than
346 * or equal to {@code bound}
347 */
348 public int nextInt(int origin, int bound) {
349 if (origin >= bound)
350 throw new IllegalArgumentException(BAD_RANGE);
351 return internalNextInt(origin, bound);
352 }
353
354 /**
355 * Returns a pseudorandom {@code long} value.
356 *
357 * @return a pseudorandom {@code long} value
358 */
359 public long nextLong() {
360 return mix64(nextSeed());
361 }
362
363 /**
364 * Returns a pseudorandom {@code long} value between zero (inclusive)
365 * and the specified bound (exclusive).
366 *
367 * @param bound the upper bound (exclusive). Must be positive.
368 * @return a pseudorandom {@code long} value between zero
369 * (inclusive) and the bound (exclusive)
370 * @throws IllegalArgumentException if {@code bound} is not positive
371 */
372 public long nextLong(long bound) {
373 if (bound <= 0)
374 throw new IllegalArgumentException(BAD_BOUND);
375 long r = mix64(nextSeed());
376 long m = bound - 1;
377 if ((bound & m) == 0L) // power of two
378 r &= m;
379 else { // reject over-represented candidates
380 for (long u = r >>> 1;
381 u + m - (r = u % bound) < 0L;
382 u = mix64(nextSeed()) >>> 1)
383 ;
384 }
385 return r;
386 }
387
388 /**
389 * Returns a pseudorandom {@code long} value between the specified
390 * origin (inclusive) and the specified bound (exclusive).
391 *
392 * @param origin the least value returned
393 * @param bound the upper bound (exclusive)
394 * @return a pseudorandom {@code long} value between the origin
395 * (inclusive) and the bound (exclusive)
396 * @throws IllegalArgumentException if {@code origin} is greater than
397 * or equal to {@code bound}
398 */
399 public long nextLong(long origin, long bound) {
400 if (origin >= bound)
401 throw new IllegalArgumentException(BAD_RANGE);
402 return internalNextLong(origin, bound);
403 }
404
405 /**
406 * Returns a pseudorandom {@code double} value between zero
407 * (inclusive) and one (exclusive).
408 *
409 * @return a pseudorandom {@code double} value between zero
410 * (inclusive) and one (exclusive)
411 */
412 public double nextDouble() {
413 return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
414 }
415
416 /**
417 * Returns a pseudorandom {@code double} value between 0.0
418 * (inclusive) and the specified bound (exclusive).
419 *
420 * @param bound the upper bound (exclusive). Must be positive.
421 * @return a pseudorandom {@code double} value between zero
422 * (inclusive) and the bound (exclusive)
423 * @throws IllegalArgumentException if {@code bound} is not positive
424 */
425 public double nextDouble(double bound) {
426 if (!(bound > 0.0))
427 throw new IllegalArgumentException(BAD_BOUND);
428 double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
429 return (result < bound) ? result : // correct for rounding
430 Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
431 }
432
433 /**
434 * Returns a pseudorandom {@code double} value between the specified
435 * origin (inclusive) and bound (exclusive).
436 *
437 * @param origin the least value returned
438 * @param bound the upper bound (exclusive)
439 * @return a pseudorandom {@code double} value between the origin
440 * (inclusive) and the bound (exclusive)
441 * @throws IllegalArgumentException if {@code origin} is greater than
442 * or equal to {@code bound}
443 */
444 public double nextDouble(double origin, double bound) {
445 if (!(origin < bound))
446 throw new IllegalArgumentException(BAD_RANGE);
447 return internalNextDouble(origin, bound);
448 }
449
450 /**
451 * Returns a pseudorandom {@code boolean} value.
452 *
453 * @return a pseudorandom {@code boolean} value
454 */
455 public boolean nextBoolean() {
456 return mix32(nextSeed()) < 0;
457 }
458
459 /**
460 * Returns a pseudorandom {@code float} value between zero
461 * (inclusive) and one (exclusive).
462 *
463 * @return a pseudorandom {@code float} value between zero
464 * (inclusive) and one (exclusive)
465 */
466 public float nextFloat() {
467 return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
468 }
469
470 public double nextGaussian() {
471 // Use nextLocalGaussian instead of nextGaussian field
472 Double d = nextLocalGaussian.get();
473 if (d != null) {
474 nextLocalGaussian.set(null);
475 return d.doubleValue();
476 }
477 double v1, v2, s;
478 do {
479 v1 = 2 * nextDouble() - 1; // between -1 and 1
480 v2 = 2 * nextDouble() - 1; // between -1 and 1
481 s = v1 * v1 + v2 * v2;
482 } while (s >= 1 || s == 0);
483 double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
484 nextLocalGaussian.set(new Double(v2 * multiplier));
485 return v1 * multiplier;
486 }
487
488 // stream methods, coded in a way intended to better isolate for
489 // maintenance purposes the small differences across forms.
490
491 /**
492 * Returns a stream producing the given {@code streamSize} number of
493 * pseudorandom {@code int} values.
494 *
495 * @param streamSize the number of values to generate
496 * @return a stream of pseudorandom {@code int} values
497 * @throws IllegalArgumentException if {@code streamSize} is
498 * less than zero
499 * @since 1.8
500 */
501 public IntStream ints(long streamSize) {
502 if (streamSize < 0L)
503 throw new IllegalArgumentException(BAD_SIZE);
504 return StreamSupport.intStream
505 (new RandomIntsSpliterator
506 (0L, streamSize, Integer.MAX_VALUE, 0),
507 false);
508 }
509
510 /**
511 * Returns an effectively unlimited stream of pseudorandom {@code int}
512 * values.
513 *
514 * @implNote This method is implemented to be equivalent to {@code
515 * ints(Long.MAX_VALUE)}.
516 *
517 * @return a stream of pseudorandom {@code int} values
518 * @since 1.8
519 */
520 public IntStream ints() {
521 return StreamSupport.intStream
522 (new RandomIntsSpliterator
523 (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
524 false);
525 }
526
527 /**
528 * Returns a stream producing the given {@code streamSize} number
529 * of pseudorandom {@code int} values, each conforming to the given
530 * origin (inclusive) and bound (exclusive).
531 *
532 * @param streamSize the number of values to generate
533 * @param randomNumberOrigin the origin (inclusive) of each random value
534 * @param randomNumberBound the bound (exclusive) of each random value
535 * @return a stream of pseudorandom {@code int} values,
536 * each with the given origin (inclusive) and bound (exclusive)
537 * @throws IllegalArgumentException if {@code streamSize} is
538 * less than zero, or {@code randomNumberOrigin}
539 * is greater than or equal to {@code randomNumberBound}
540 * @since 1.8
541 */
542 public IntStream ints(long streamSize, int randomNumberOrigin,
543 int randomNumberBound) {
544 if (streamSize < 0L)
545 throw new IllegalArgumentException(BAD_SIZE);
546 if (randomNumberOrigin >= randomNumberBound)
547 throw new IllegalArgumentException(BAD_RANGE);
548 return StreamSupport.intStream
549 (new RandomIntsSpliterator
550 (0L, streamSize, randomNumberOrigin, randomNumberBound),
551 false);
552 }
553
554 /**
555 * Returns an effectively unlimited stream of pseudorandom {@code
556 * int} values, each conforming to the given origin (inclusive) and bound
557 * (exclusive).
558 *
559 * @implNote This method is implemented to be equivalent to {@code
560 * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
561 *
562 * @param randomNumberOrigin the origin (inclusive) of each random value
563 * @param randomNumberBound the bound (exclusive) of each random value
564 * @return a stream of pseudorandom {@code int} values,
565 * each with the given origin (inclusive) and bound (exclusive)
566 * @throws IllegalArgumentException if {@code randomNumberOrigin}
567 * is greater than or equal to {@code randomNumberBound}
568 * @since 1.8
569 */
570 public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
571 if (randomNumberOrigin >= randomNumberBound)
572 throw new IllegalArgumentException(BAD_RANGE);
573 return StreamSupport.intStream
574 (new RandomIntsSpliterator
575 (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
576 false);
577 }
578
579 /**
580 * Returns a stream producing the given {@code streamSize} number of
581 * pseudorandom {@code long} values.
582 *
583 * @param streamSize the number of values to generate
584 * @return a stream of pseudorandom {@code long} values
585 * @throws IllegalArgumentException if {@code streamSize} is
586 * less than zero
587 * @since 1.8
588 */
589 public LongStream longs(long streamSize) {
590 if (streamSize < 0L)
591 throw new IllegalArgumentException(BAD_SIZE);
592 return StreamSupport.longStream
593 (new RandomLongsSpliterator
594 (0L, streamSize, Long.MAX_VALUE, 0L),
595 false);
596 }
597
598 /**
599 * Returns an effectively unlimited stream of pseudorandom {@code long}
600 * values.
601 *
602 * @implNote This method is implemented to be equivalent to {@code
603 * longs(Long.MAX_VALUE)}.
604 *
605 * @return a stream of pseudorandom {@code long} values
606 * @since 1.8
607 */
608 public LongStream longs() {
609 return StreamSupport.longStream
610 (new RandomLongsSpliterator
611 (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
612 false);
613 }
614
615 /**
616 * Returns a stream producing the given {@code streamSize} number of
617 * pseudorandom {@code long}, each conforming to the given origin
618 * (inclusive) and bound (exclusive).
619 *
620 * @param streamSize the number of values to generate
621 * @param randomNumberOrigin the origin (inclusive) of each random value
622 * @param randomNumberBound the bound (exclusive) of each random value
623 * @return a stream of pseudorandom {@code long} values,
624 * each with the given origin (inclusive) and bound (exclusive)
625 * @throws IllegalArgumentException if {@code streamSize} is
626 * less than zero, or {@code randomNumberOrigin}
627 * is greater than or equal to {@code randomNumberBound}
628 * @since 1.8
629 */
630 public LongStream longs(long streamSize, long randomNumberOrigin,
631 long randomNumberBound) {
632 if (streamSize < 0L)
633 throw new IllegalArgumentException(BAD_SIZE);
634 if (randomNumberOrigin >= randomNumberBound)
635 throw new IllegalArgumentException(BAD_RANGE);
636 return StreamSupport.longStream
637 (new RandomLongsSpliterator
638 (0L, streamSize, randomNumberOrigin, randomNumberBound),
639 false);
640 }
641
642 /**
643 * Returns an effectively unlimited stream of pseudorandom {@code
644 * long} values, each conforming to the given origin (inclusive) and bound
645 * (exclusive).
646 *
647 * @implNote This method is implemented to be equivalent to {@code
648 * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
649 *
650 * @param randomNumberOrigin the origin (inclusive) of each random value
651 * @param randomNumberBound the bound (exclusive) of each random value
652 * @return a stream of pseudorandom {@code long} values,
653 * each with the given origin (inclusive) and bound (exclusive)
654 * @throws IllegalArgumentException if {@code randomNumberOrigin}
655 * is greater than or equal to {@code randomNumberBound}
656 * @since 1.8
657 */
658 public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
659 if (randomNumberOrigin >= randomNumberBound)
660 throw new IllegalArgumentException(BAD_RANGE);
661 return StreamSupport.longStream
662 (new RandomLongsSpliterator
663 (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
664 false);
665 }
666
667 /**
668 * Returns a stream producing the given {@code streamSize} number of
669 * pseudorandom {@code double} values, each between zero
670 * (inclusive) and one (exclusive).
671 *
672 * @param streamSize the number of values to generate
673 * @return a stream of {@code double} values
674 * @throws IllegalArgumentException if {@code streamSize} is
675 * less than zero
676 * @since 1.8
677 */
678 public DoubleStream doubles(long streamSize) {
679 if (streamSize < 0L)
680 throw new IllegalArgumentException(BAD_SIZE);
681 return StreamSupport.doubleStream
682 (new RandomDoublesSpliterator
683 (0L, streamSize, Double.MAX_VALUE, 0.0),
684 false);
685 }
686
687 /**
688 * Returns an effectively unlimited stream of pseudorandom {@code
689 * double} values, each between zero (inclusive) and one
690 * (exclusive).
691 *
692 * @implNote This method is implemented to be equivalent to {@code
693 * doubles(Long.MAX_VALUE)}.
694 *
695 * @return a stream of pseudorandom {@code double} values
696 * @since 1.8
697 */
698 public DoubleStream doubles() {
699 return StreamSupport.doubleStream
700 (new RandomDoublesSpliterator
701 (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
702 false);
703 }
704
705 /**
706 * Returns a stream producing the given {@code streamSize} number of
707 * pseudorandom {@code double} values, each conforming to the given origin
708 * (inclusive) and bound (exclusive).
709 *
710 * @param streamSize the number of values to generate
711 * @param randomNumberOrigin the origin (inclusive) of each random value
712 * @param randomNumberBound the bound (exclusive) of each random value
713 * @return a stream of pseudorandom {@code double} values,
714 * each with the given origin (inclusive) and bound (exclusive)
715 * @throws IllegalArgumentException if {@code streamSize} is
716 * less than zero
717 * @throws IllegalArgumentException if {@code randomNumberOrigin}
718 * is greater than or equal to {@code randomNumberBound}
719 * @since 1.8
720 */
721 public DoubleStream doubles(long streamSize, double randomNumberOrigin,
722 double randomNumberBound) {
723 if (streamSize < 0L)
724 throw new IllegalArgumentException(BAD_SIZE);
725 if (!(randomNumberOrigin < randomNumberBound))
726 throw new IllegalArgumentException(BAD_RANGE);
727 return StreamSupport.doubleStream
728 (new RandomDoublesSpliterator
729 (0L, streamSize, randomNumberOrigin, randomNumberBound),
730 false);
731 }
732
733 /**
734 * Returns an effectively unlimited stream of pseudorandom {@code
735 * double} values, each conforming to the given origin (inclusive) and bound
736 * (exclusive).
737 *
738 * @implNote This method is implemented to be equivalent to {@code
739 * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
740 *
741 * @param randomNumberOrigin the origin (inclusive) of each random value
742 * @param randomNumberBound the bound (exclusive) of each random value
743 * @return a stream of pseudorandom {@code double} values,
744 * each with the given origin (inclusive) and bound (exclusive)
745 * @throws IllegalArgumentException if {@code randomNumberOrigin}
746 * is greater than or equal to {@code randomNumberBound}
747 * @since 1.8
748 */
749 public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
750 if (!(randomNumberOrigin < randomNumberBound))
751 throw new IllegalArgumentException(BAD_RANGE);
752 return StreamSupport.doubleStream
753 (new RandomDoublesSpliterator
754 (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
755 false);
756 }
757
758 /**
759 * Spliterator for int streams. We multiplex the four int
760 * versions into one class by treating a bound less than origin as
761 * unbounded, and also by treating "infinite" as equivalent to
762 * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
763 * approach. The long and double versions of this class are
764 * identical except for types.
765 */
766 private static final class RandomIntsSpliterator
767 implements Spliterator.OfInt {
768 long index;
769 final long fence;
770 final int origin;
771 final int bound;
772 RandomIntsSpliterator(long index, long fence,
773 int origin, int bound) {
774 this.index = index; this.fence = fence;
775 this.origin = origin; this.bound = bound;
776 }
777
778 public RandomIntsSpliterator trySplit() {
779 long i = index, m = (i + fence) >>> 1;
780 return (m <= i) ? null :
781 new RandomIntsSpliterator(i, index = m, origin, bound);
782 }
783
784 public long estimateSize() {
785 return fence - index;
786 }
787
788 public int characteristics() {
789 return (Spliterator.SIZED | Spliterator.SUBSIZED |
790 Spliterator.NONNULL | Spliterator.IMMUTABLE);
791 }
792
793 public boolean tryAdvance(IntConsumer consumer) {
794 if (consumer == null) throw new NullPointerException();
795 long i = index, f = fence;
796 if (i < f) {
797 consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
798 index = i + 1;
799 return true;
800 }
801 return false;
802 }
803
804 public void forEachRemaining(IntConsumer consumer) {
805 if (consumer == null) throw new NullPointerException();
806 long i = index, f = fence;
807 if (i < f) {
808 index = f;
809 int o = origin, b = bound;
810 ThreadLocalRandom rng = ThreadLocalRandom.current();
811 do {
812 consumer.accept(rng.internalNextInt(o, b));
813 } while (++i < f);
814 }
815 }
816 }
817
818 /**
819 * Spliterator for long streams.
820 */
821 private static final class RandomLongsSpliterator
822 implements Spliterator.OfLong {
823 long index;
824 final long fence;
825 final long origin;
826 final long bound;
827 RandomLongsSpliterator(long index, long fence,
828 long origin, long bound) {
829 this.index = index; this.fence = fence;
830 this.origin = origin; this.bound = bound;
831 }
832
833 public RandomLongsSpliterator trySplit() {
834 long i = index, m = (i + fence) >>> 1;
835 return (m <= i) ? null :
836 new RandomLongsSpliterator(i, index = m, origin, bound);
837 }
838
839 public long estimateSize() {
840 return fence - index;
841 }
842
843 public int characteristics() {
844 return (Spliterator.SIZED | Spliterator.SUBSIZED |
845 Spliterator.NONNULL | Spliterator.IMMUTABLE);
846 }
847
848 public boolean tryAdvance(LongConsumer consumer) {
849 if (consumer == null) throw new NullPointerException();
850 long i = index, f = fence;
851 if (i < f) {
852 consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
853 index = i + 1;
854 return true;
855 }
856 return false;
857 }
858
859 public void forEachRemaining(LongConsumer consumer) {
860 if (consumer == null) throw new NullPointerException();
861 long i = index, f = fence;
862 if (i < f) {
863 index = f;
864 long o = origin, b = bound;
865 ThreadLocalRandom rng = ThreadLocalRandom.current();
866 do {
867 consumer.accept(rng.internalNextLong(o, b));
868 } while (++i < f);
869 }
870 }
871
872 }
873
874 /**
875 * Spliterator for double streams.
876 */
877 private static final class RandomDoublesSpliterator
878 implements Spliterator.OfDouble {
879 long index;
880 final long fence;
881 final double origin;
882 final double bound;
883 RandomDoublesSpliterator(long index, long fence,
884 double origin, double bound) {
885 this.index = index; this.fence = fence;
886 this.origin = origin; this.bound = bound;
887 }
888
889 public RandomDoublesSpliterator trySplit() {
890 long i = index, m = (i + fence) >>> 1;
891 return (m <= i) ? null :
892 new RandomDoublesSpliterator(i, index = m, origin, bound);
893 }
894
895 public long estimateSize() {
896 return fence - index;
897 }
898
899 public int characteristics() {
900 return (Spliterator.SIZED | Spliterator.SUBSIZED |
901 Spliterator.NONNULL | Spliterator.IMMUTABLE);
902 }
903
904 public boolean tryAdvance(DoubleConsumer consumer) {
905 if (consumer == null) throw new NullPointerException();
906 long i = index, f = fence;
907 if (i < f) {
908 consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
909 index = i + 1;
910 return true;
911 }
912 return false;
913 }
914
915 public void forEachRemaining(DoubleConsumer consumer) {
916 if (consumer == null) throw new NullPointerException();
917 long i = index, f = fence;
918 if (i < f) {
919 index = f;
920 double o = origin, b = bound;
921 ThreadLocalRandom rng = ThreadLocalRandom.current();
922 do {
923 consumer.accept(rng.internalNextDouble(o, b));
924 } while (++i < f);
925 }
926 }
927 }
928
929
930 // Within-package utilities
931
932 /*
933 * Descriptions of the usages of the methods below can be found in
934 * the classes that use them. Briefly, a thread's "probe" value is
935 * a non-zero hash code that (probably) does not collide with
936 * other existing threads with respect to any power of two
937 * collision space. When it does collide, it is pseudo-randomly
938 * adjusted (using a Marsaglia XorShift). The nextSecondarySeed
939 * method is used in the same contexts as ThreadLocalRandom, but
940 * only for transient usages such as random adaptive spin/block
941 * sequences for which a cheap RNG suffices and for which it could
942 * in principle disrupt user-visible statistical properties of the
943 * main ThreadLocalRandom if we were to use it.
944 *
945 * Note: Because of package-protection issues, versions of some
946 * these methods also appear in some subpackage classes.
947 */
948
949 /**
950 * Returns the probe value for the current thread without forcing
951 * initialization. Note that invoking ThreadLocalRandom.current()
952 * can be used to force initialization on zero return.
953 */
954 static final int getProbe() {
955 return U.getInt(Thread.currentThread(), PROBE);
956 }
957
958 /**
959 * Pseudo-randomly advances and records the given probe value for the
960 * given thread.
961 */
962 static final int advanceProbe(int probe) {
963 probe ^= probe << 13; // xorshift
964 probe ^= probe >>> 17;
965 probe ^= probe << 5;
966 U.putInt(Thread.currentThread(), PROBE, probe);
967 return probe;
968 }
969
970 /**
971 * Returns the pseudo-randomly initialized or updated secondary seed.
972 */
973 static final int nextSecondarySeed() {
974 int r;
975 Thread t = Thread.currentThread();
976 if ((r = U.getInt(t, SECONDARY)) != 0) {
977 r ^= r << 13; // xorshift
978 r ^= r >>> 17;
979 r ^= r << 5;
980 }
981 else if ((r = mix32(seeder.getAndAdd(SEEDER_INCREMENT))) == 0)
982 r = 1; // avoid zero
983 U.putInt(t, SECONDARY, r);
984 return r;
985 }
986
987 // Serialization support
988
989 private static final long serialVersionUID = -5851777807851030925L;
990
991 /**
992 * @serialField rnd long
993 * seed for random computations
994 * @serialField initialized boolean
995 * always true
996 */
997 private static final ObjectStreamField[] serialPersistentFields = {
998 new ObjectStreamField("rnd", long.class),
999 new ObjectStreamField("initialized", boolean.class),
1000 };
1001
1002 /**
1003 * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
1004 * @param s the stream
1005 * @throws java.io.IOException if an I/O error occurs
1006 */
1007 private void writeObject(java.io.ObjectOutputStream s)
1008 throws java.io.IOException {
1009
1010 java.io.ObjectOutputStream.PutField fields = s.putFields();
1011 fields.put("rnd", U.getLong(Thread.currentThread(), SEED));
1012 fields.put("initialized", true);
1013 s.writeFields();
1014 }
1015
1016 /**
1017 * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}.
1018 * @return the {@link #current() current} thread's {@code ThreadLocalRandom}
1019 */
1020 private Object readResolve() {
1021 return current();
1022 }
1023
1024 // Unsafe mechanics
1025 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1026 private static final long SEED;
1027 private static final long PROBE;
1028 private static final long SECONDARY;
1029 static {
1030 try {
1031 SEED = U.objectFieldOffset
1032 (Thread.class.getDeclaredField("threadLocalRandomSeed"));
1033 PROBE = U.objectFieldOffset
1034 (Thread.class.getDeclaredField("threadLocalRandomProbe"));
1035 SECONDARY = U.objectFieldOffset
1036 (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed"));
1037 } catch (ReflectiveOperationException e) {
1038 throw new Error(e);
1039 }
1040 }
1041 }