ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.45
Committed: Thu Jun 2 13:40:42 2016 UTC (8 years ago) by jsr166
Branch: MAIN
Changes since 1.44: +2 -2 lines
Log Message:
whitespace

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