ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.61
Committed: Sat Aug 10 16:48:05 2019 UTC (4 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +12 -24 lines
Log Message:
drop support for jdk9 and jdk10; drop backward compatibility hacks

File Contents

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