ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.48
Committed: Sun Nov 13 02:23:22 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.47: +1 -1 lines
Log Message:
typo

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 jsr166 1.1
24     /**
25 jsr166 1.3 * A random number generator isolated to the current thread. Like the
26 jsr166 1.2 * global {@link java.util.Random} generator used by the {@link
27 jsr166 1.3 * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
28     * with an internally generated seed that may not otherwise be
29     * modified. When applicable, use of {@code ThreadLocalRandom} rather
30     * than shared {@code Random} objects in concurrent programs will
31     * typically encounter much less overhead and contention. Use of
32     * {@code ThreadLocalRandom} is particularly appropriate when multiple
33     * tasks (for example, each a {@link ForkJoinTask}) use random numbers
34     * in parallel in thread pools.
35 jsr166 1.1 *
36     * <p>Usages of this class should typically be of the form:
37     * {@code ThreadLocalRandom.current().nextX(...)} (where
38     * {@code X} is {@code Int}, {@code Long}, etc).
39     * When all usages are of this form, it is never possible to
40 jsr166 1.3 * accidently share a {@code ThreadLocalRandom} across multiple threads.
41 jsr166 1.1 *
42     * <p>This class also provides additional commonly used bounded random
43     * generation methods.
44     *
45 dl 1.21 * <p>Instances of {@code ThreadLocalRandom} are not cryptographically
46     * secure. Consider instead using {@link java.security.SecureRandom}
47 dl 1.23 * in security-sensitive applications. Additionally,
48     * default-constructed instances do not use a cryptographically random
49     * seed unless the {@linkplain System#getProperty system property}
50     * {@code java.util.secureRandomSeed} is set to {@code true}.
51 dl 1.21 *
52 jsr166 1.1 * @since 1.7
53     * @author Doug Lea
54     */
55     public class ThreadLocalRandom extends Random {
56 dl 1.7 /*
57     * This class implements the java.util.Random API (and subclasses
58     * Random) using a single static instance that accesses random
59     * number state held in class Thread (primarily, field
60     * threadLocalRandomSeed). In doing so, it also provides a home
61     * for managing package-private utilities that rely on exactly the
62     * same state as needed to maintain the ThreadLocalRandom
63     * instances. We leverage the need for an initialization flag
64     * field to also use it as a "probe" -- a self-adjusting thread
65     * hash used for contention avoidance, as well as a secondary
66     * simpler (xorShift) random seed that is conservatively used to
67     * avoid otherwise surprising users by hijacking the
68     * ThreadLocalRandom sequence. The dual use is a marriage of
69     * convenience, but is a simple and efficient way of reducing
70     * application-level overhead and footprint of most concurrent
71 dl 1.44 * programs. Even more opportunistically, we also define here
72     * other package-private utilities that access Thread class
73     * fields.
74 dl 1.7 *
75 dl 1.19 * Even though this class subclasses java.util.Random, it uses the
76     * same basic algorithm as java.util.SplittableRandom. (See its
77     * internal documentation for explanations, which are not repeated
78     * here.) Because ThreadLocalRandoms are not splittable
79     * though, we use only a single 64bit gamma.
80     *
81 dl 1.7 * Because this class is in a different package than class Thread,
82 jsr166 1.15 * field access methods use Unsafe to bypass access control rules.
83 dl 1.19 * To conform to the requirements of the Random superclass
84     * constructor, the common static ThreadLocalRandom maintains an
85     * "initialized" field for the sake of rejecting user calls to
86     * setSeed while still allowing a call from constructor. Note
87     * that serialization is completely unnecessary because there is
88     * only a static singleton. But we generate a serial form
89     * containing "rnd" and "initialized" fields to ensure
90     * compatibility across versions.
91     *
92     * Implementations of non-core methods are mostly the same as in
93     * SplittableRandom, that were in part derived from a previous
94     * version of this class.
95 dl 1.7 *
96     * The nextLocalGaussian ThreadLocal supports the very rarely used
97     * nextGaussian method by providing a holder for the second of a
98     * pair of them. As is true for the base class version of this
99     * method, this time/space tradeoff is probably never worthwhile,
100     * but we provide identical statistical properties.
101     */
102    
103 dl 1.19 private static long mix64(long z) {
104     z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
105     z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
106     return z ^ (z >>> 33);
107     }
108    
109     private static int mix32(long z) {
110     z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
111     return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
112     }
113    
114 jsr166 1.11 /**
115     * Field used only during singleton initialization.
116     * True when constructor completes.
117 jsr166 1.1 */
118 jsr166 1.11 boolean initialized;
119 dl 1.7
120     /** Constructor used only for static singleton */
121     private ThreadLocalRandom() {
122     initialized = true; // false during super() call
123     }
124 jsr166 1.1
125     /**
126 dl 1.7 * Initialize Thread fields for the current thread. Called only
127     * when Thread.threadLocalRandomProbe is zero, indicating that a
128     * thread local seed value needs to be generated. Note that even
129     * though the initialization is purely thread-local, we need to
130     * rely on (static) atomic generators to initialize the values.
131     */
132     static final void localInit() {
133 dl 1.19 int p = probeGenerator.addAndGet(PROBE_INCREMENT);
134 dl 1.7 int probe = (p == 0) ? 1 : p; // skip 0
135 dl 1.21 long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
136 dl 1.7 Thread t = Thread.currentThread();
137 jsr166 1.33 U.putLong(t, SEED, seed);
138     U.putInt(t, PROBE, probe);
139 jsr166 1.1 }
140    
141     /**
142 jsr166 1.3 * Returns the current thread's {@code ThreadLocalRandom}.
143 jsr166 1.1 *
144 jsr166 1.3 * @return the current thread's {@code ThreadLocalRandom}
145 jsr166 1.1 */
146     public static ThreadLocalRandom current() {
147 jsr166 1.33 if (U.getInt(Thread.currentThread(), PROBE) == 0)
148 dl 1.7 localInit();
149     return instance;
150 jsr166 1.1 }
151    
152     /**
153 jsr166 1.3 * Throws {@code UnsupportedOperationException}. Setting seeds in
154     * this generator is not supported.
155 jsr166 1.1 *
156     * @throws UnsupportedOperationException always
157     */
158     public void setSeed(long seed) {
159 jsr166 1.15 // only allow call from super() constructor
160     if (initialized)
161 jsr166 1.1 throw new UnsupportedOperationException();
162     }
163    
164 dl 1.19 final long nextSeed() {
165     Thread t; long r; // read and update per-thread seed
166 jsr166 1.33 U.putLong(t = Thread.currentThread(), SEED,
167 jsr166 1.34 r = U.getLong(t, SEED) + GAMMA);
168 dl 1.19 return r;
169     }
170    
171 dl 1.47 /**
172     * Generates a pseudorandom number with the indicated number of
173 jsr166 1.48 * bits. Unlike in superclass {@link Random}, this method is never
174 dl 1.47 * internally called or used by any other publicly accessible
175     * method.
176     *
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 dl 1.19 return (int)(mix64(nextSeed()) >>> (64 - bits));
183     }
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 dl 1.21 * less than zero
675 dl 1.19 * @throws IllegalArgumentException if {@code randomNumberOrigin}
676     * is greater than or equal to {@code randomNumberBound}
677 dl 1.21 * @since 1.8
678 dl 1.19 */
679     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
680     double randomNumberBound) {
681     if (streamSize < 0L)
682 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
683 dl 1.19 if (!(randomNumberOrigin < randomNumberBound))
684 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
685 dl 1.19 return StreamSupport.doubleStream
686     (new RandomDoublesSpliterator
687     (0L, streamSize, randomNumberOrigin, randomNumberBound),
688     false);
689     }
690    
691     /**
692     * Returns an effectively unlimited stream of pseudorandom {@code
693 dl 1.21 * double} values, each conforming to the given origin (inclusive) and bound
694     * (exclusive).
695 dl 1.19 *
696     * @implNote This method is implemented to be equivalent to {@code
697     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
698     *
699 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
700     * @param randomNumberBound the bound (exclusive) of each random value
701 dl 1.19 * @return a stream of pseudorandom {@code double} values,
702 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
703 dl 1.19 * @throws IllegalArgumentException if {@code randomNumberOrigin}
704     * is greater than or equal to {@code randomNumberBound}
705 dl 1.21 * @since 1.8
706 dl 1.19 */
707     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
708     if (!(randomNumberOrigin < randomNumberBound))
709 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
710 dl 1.19 return StreamSupport.doubleStream
711     (new RandomDoublesSpliterator
712     (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
713     false);
714     }
715    
716     /**
717     * Spliterator for int streams. We multiplex the four int
718     * versions into one class by treating a bound less than origin as
719     * unbounded, and also by treating "infinite" as equivalent to
720     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
721     * approach. The long and double versions of this class are
722     * identical except for types.
723     */
724 jsr166 1.37 private static final class RandomIntsSpliterator
725     implements Spliterator.OfInt {
726 dl 1.19 long index;
727     final long fence;
728     final int origin;
729     final int bound;
730     RandomIntsSpliterator(long index, long fence,
731     int origin, int bound) {
732     this.index = index; this.fence = fence;
733     this.origin = origin; this.bound = bound;
734     }
735    
736     public RandomIntsSpliterator trySplit() {
737     long i = index, m = (i + fence) >>> 1;
738     return (m <= i) ? null :
739     new RandomIntsSpliterator(i, index = m, origin, bound);
740     }
741    
742     public long estimateSize() {
743     return fence - index;
744     }
745    
746     public int characteristics() {
747     return (Spliterator.SIZED | Spliterator.SUBSIZED |
748     Spliterator.NONNULL | Spliterator.IMMUTABLE);
749     }
750    
751     public boolean tryAdvance(IntConsumer consumer) {
752     if (consumer == null) throw new NullPointerException();
753     long i = index, f = fence;
754     if (i < f) {
755     consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
756     index = i + 1;
757     return true;
758     }
759     return false;
760     }
761    
762     public void forEachRemaining(IntConsumer consumer) {
763     if (consumer == null) throw new NullPointerException();
764     long i = index, f = fence;
765     if (i < f) {
766     index = f;
767     int o = origin, b = bound;
768     ThreadLocalRandom rng = ThreadLocalRandom.current();
769     do {
770     consumer.accept(rng.internalNextInt(o, b));
771     } while (++i < f);
772     }
773     }
774     }
775    
776     /**
777     * Spliterator for long streams.
778     */
779 jsr166 1.37 private static final class RandomLongsSpliterator
780     implements Spliterator.OfLong {
781 dl 1.19 long index;
782     final long fence;
783     final long origin;
784     final long bound;
785     RandomLongsSpliterator(long index, long fence,
786     long origin, long bound) {
787     this.index = index; this.fence = fence;
788     this.origin = origin; this.bound = bound;
789     }
790    
791     public RandomLongsSpliterator trySplit() {
792     long i = index, m = (i + fence) >>> 1;
793     return (m <= i) ? null :
794     new RandomLongsSpliterator(i, index = m, origin, bound);
795     }
796    
797     public long estimateSize() {
798     return fence - index;
799     }
800    
801     public int characteristics() {
802     return (Spliterator.SIZED | Spliterator.SUBSIZED |
803     Spliterator.NONNULL | Spliterator.IMMUTABLE);
804     }
805    
806     public boolean tryAdvance(LongConsumer consumer) {
807     if (consumer == null) throw new NullPointerException();
808     long i = index, f = fence;
809     if (i < f) {
810     consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
811     index = i + 1;
812     return true;
813     }
814     return false;
815     }
816    
817     public void forEachRemaining(LongConsumer consumer) {
818     if (consumer == null) throw new NullPointerException();
819     long i = index, f = fence;
820     if (i < f) {
821     index = f;
822     long o = origin, b = bound;
823     ThreadLocalRandom rng = ThreadLocalRandom.current();
824     do {
825     consumer.accept(rng.internalNextLong(o, b));
826     } while (++i < f);
827     }
828     }
829    
830     }
831    
832     /**
833     * Spliterator for double streams.
834     */
835 jsr166 1.37 private static final class RandomDoublesSpliterator
836     implements Spliterator.OfDouble {
837 dl 1.19 long index;
838     final long fence;
839     final double origin;
840     final double bound;
841     RandomDoublesSpliterator(long index, long fence,
842     double origin, double bound) {
843     this.index = index; this.fence = fence;
844     this.origin = origin; this.bound = bound;
845     }
846    
847     public RandomDoublesSpliterator trySplit() {
848     long i = index, m = (i + fence) >>> 1;
849     return (m <= i) ? null :
850     new RandomDoublesSpliterator(i, index = m, origin, bound);
851     }
852    
853     public long estimateSize() {
854     return fence - index;
855     }
856    
857     public int characteristics() {
858     return (Spliterator.SIZED | Spliterator.SUBSIZED |
859     Spliterator.NONNULL | Spliterator.IMMUTABLE);
860     }
861    
862     public boolean tryAdvance(DoubleConsumer consumer) {
863     if (consumer == null) throw new NullPointerException();
864     long i = index, f = fence;
865     if (i < f) {
866     consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
867     index = i + 1;
868     return true;
869     }
870     return false;
871     }
872    
873     public void forEachRemaining(DoubleConsumer consumer) {
874     if (consumer == null) throw new NullPointerException();
875     long i = index, f = fence;
876     if (i < f) {
877     index = f;
878     double o = origin, b = bound;
879     ThreadLocalRandom rng = ThreadLocalRandom.current();
880     do {
881     consumer.accept(rng.internalNextDouble(o, b));
882     } while (++i < f);
883     }
884     }
885     }
886    
887    
888 dl 1.7 // Within-package utilities
889    
890     /*
891     * Descriptions of the usages of the methods below can be found in
892     * the classes that use them. Briefly, a thread's "probe" value is
893     * a non-zero hash code that (probably) does not collide with
894     * other existing threads with respect to any power of two
895     * collision space. When it does collide, it is pseudo-randomly
896     * adjusted (using a Marsaglia XorShift). The nextSecondarySeed
897     * method is used in the same contexts as ThreadLocalRandom, but
898     * only for transient usages such as random adaptive spin/block
899     * sequences for which a cheap RNG suffices and for which it could
900     * in principle disrupt user-visible statistical properties of the
901     * main ThreadLocalRandom if we were to use it.
902     *
903     * Note: Because of package-protection issues, versions of some
904 dl 1.9 * these methods also appear in some subpackage classes.
905 dl 1.7 */
906    
907     /**
908     * Returns the probe value for the current thread without forcing
909     * initialization. Note that invoking ThreadLocalRandom.current()
910     * can be used to force initialization on zero return.
911     */
912     static final int getProbe() {
913 jsr166 1.33 return U.getInt(Thread.currentThread(), PROBE);
914 dl 1.7 }
915    
916     /**
917     * Pseudo-randomly advances and records the given probe value for the
918     * given thread.
919     */
920     static final int advanceProbe(int probe) {
921     probe ^= probe << 13; // xorshift
922     probe ^= probe >>> 17;
923     probe ^= probe << 5;
924 jsr166 1.33 U.putInt(Thread.currentThread(), PROBE, probe);
925 dl 1.7 return probe;
926     }
927    
928     /**
929     * Returns the pseudo-randomly initialized or updated secondary seed.
930     */
931     static final int nextSecondarySeed() {
932     int r;
933     Thread t = Thread.currentThread();
934 jsr166 1.33 if ((r = U.getInt(t, SECONDARY)) != 0) {
935 dl 1.7 r ^= r << 13; // xorshift
936     r ^= r >>> 17;
937     r ^= r << 5;
938     }
939 dl 1.28 else if ((r = mix32(seeder.getAndAdd(SEEDER_INCREMENT))) == 0)
940 jsr166 1.29 r = 1; // avoid zero
941 jsr166 1.33 U.putInt(t, SECONDARY, r);
942 dl 1.7 return r;
943     }
944    
945 dl 1.44 // Support for other package-private ThreadLocal access
946    
947     /**
948     * Erases ThreadLocals by nulling out Thread maps.
949     */
950     static final void eraseThreadLocals(Thread thread) {
951     U.putObject(thread, THREADLOCALS, null);
952     U.putObject(thread, INHERITABLETHREADLOCALS, null);
953 jsr166 1.45 }
954 dl 1.44
955     static final void setInheritedAccessControlContext(Thread thread,
956     AccessControlContext acc) {
957     U.putObjectRelease(thread, INHERITEDACCESSCONTROLCONTEXT, acc);
958     }
959    
960     /**
961     * Returns a new group with the system ThreadGroup (the
962     * topmost, parent-less group) as parent. Uses Unsafe to
963     * traverse Thread.group and ThreadGroup.parent fields.
964     */
965     static final ThreadGroup createThreadGroup(String name) {
966     if (name == null)
967     throw new NullPointerException();
968     try {
969     long tg = U.objectFieldOffset
970     (Thread.class.getDeclaredField("group"));
971     long gp = U.objectFieldOffset
972     (ThreadGroup.class.getDeclaredField("parent"));
973     ThreadGroup group = (ThreadGroup)
974     U.getObject(Thread.currentThread(), tg);
975     while (group != null) {
976     ThreadGroup parent = (ThreadGroup)U.getObject(group, gp);
977     if (parent == null)
978     return new ThreadGroup(group, name);
979     group = parent;
980     }
981     } catch (ReflectiveOperationException e) {
982     throw new Error(e);
983     }
984     // fall through if null as cannot-happen safeguard
985     throw new Error("Cannot create ThreadGroup");
986     }
987 jsr166 1.45
988 jsr166 1.13 // Serialization support
989 dl 1.9
990 jsr166 1.1 private static final long serialVersionUID = -5851777807851030925L;
991 dl 1.7
992 dl 1.9 /**
993 jsr166 1.14 * @serialField rnd long
994     * seed for random computations
995     * @serialField initialized boolean
996     * always true
997     */
998     private static final ObjectStreamField[] serialPersistentFields = {
999 jsr166 1.31 new ObjectStreamField("rnd", long.class),
1000     new ObjectStreamField("initialized", boolean.class),
1001 jsr166 1.14 };
1002    
1003     /**
1004     * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
1005 jsr166 1.16 * @param s the stream
1006 jsr166 1.17 * @throws java.io.IOException if an I/O error occurs
1007 jsr166 1.14 */
1008 jsr166 1.16 private void writeObject(java.io.ObjectOutputStream s)
1009 jsr166 1.14 throws java.io.IOException {
1010    
1011 jsr166 1.16 java.io.ObjectOutputStream.PutField fields = s.putFields();
1012 jsr166 1.33 fields.put("rnd", U.getLong(Thread.currentThread(), SEED));
1013 jsr166 1.14 fields.put("initialized", true);
1014 jsr166 1.16 s.writeFields();
1015 jsr166 1.14 }
1016    
1017     /**
1018 dl 1.9 * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}.
1019 jsr166 1.16 * @return the {@link #current() current} thread's {@code ThreadLocalRandom}
1020 dl 1.9 */
1021     private Object readResolve() {
1022     return current();
1023     }
1024    
1025 jsr166 1.41 // Static initialization
1026    
1027     /**
1028     * The seed increment.
1029     */
1030     private static final long GAMMA = 0x9e3779b97f4a7c15L;
1031    
1032     /**
1033     * The increment for generating probe values.
1034     */
1035     private static final int PROBE_INCREMENT = 0x9e3779b9;
1036    
1037     /**
1038     * The increment of seeder per new instance.
1039     */
1040     private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
1041    
1042     // Constants from SplittableRandom
1043     private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
1044     private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
1045    
1046     // IllegalArgumentException messages
1047     static final String BAD_BOUND = "bound must be positive";
1048     static final String BAD_RANGE = "bound must be greater than origin";
1049     static final String BAD_SIZE = "size must be non-negative";
1050    
1051 dl 1.7 // Unsafe mechanics
1052 jsr166 1.46 private static final Unsafe U = Unsafe.getUnsafe();
1053 dl 1.7 private static final long SEED;
1054     private static final long PROBE;
1055     private static final long SECONDARY;
1056 dl 1.44 private static final long THREADLOCALS;
1057     private static final long INHERITABLETHREADLOCALS;
1058     private static final long INHERITEDACCESSCONTROLCONTEXT;
1059 dl 1.7 static {
1060     try {
1061 jsr166 1.33 SEED = U.objectFieldOffset
1062     (Thread.class.getDeclaredField("threadLocalRandomSeed"));
1063     PROBE = U.objectFieldOffset
1064     (Thread.class.getDeclaredField("threadLocalRandomProbe"));
1065     SECONDARY = U.objectFieldOffset
1066     (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed"));
1067 dl 1.44 THREADLOCALS = U.objectFieldOffset
1068     (Thread.class.getDeclaredField("threadLocals"));
1069     INHERITABLETHREADLOCALS = U.objectFieldOffset
1070     (Thread.class.getDeclaredField("inheritableThreadLocals"));
1071     INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset
1072     (Thread.class.getDeclaredField("inheritedAccessControlContext"));
1073 jsr166 1.32 } catch (ReflectiveOperationException e) {
1074 dl 1.7 throw new Error(e);
1075     }
1076     }
1077 jsr166 1.41
1078     /** Rarely-used holder for the second of a pair of Gaussians */
1079     private static final ThreadLocal<Double> nextLocalGaussian =
1080     new ThreadLocal<>();
1081    
1082     /** Generates per-thread initialization/probe field */
1083     private static final AtomicInteger probeGenerator = new AtomicInteger();
1084    
1085     /** The common ThreadLocalRandom */
1086     static final ThreadLocalRandom instance = new ThreadLocalRandom();
1087    
1088     /**
1089     * The next seed for default constructors.
1090     */
1091     private static final AtomicLong seeder
1092     = new AtomicLong(mix64(System.currentTimeMillis()) ^
1093     mix64(System.nanoTime()));
1094    
1095     // at end of <clinit> to survive static initialization circularity
1096     static {
1097     if (java.security.AccessController.doPrivileged(
1098     new java.security.PrivilegedAction<Boolean>() {
1099     public Boolean run() {
1100     return Boolean.getBoolean("java.util.secureRandomSeed");
1101     }})) {
1102     byte[] seedBytes = java.security.SecureRandom.getSeed(8);
1103     long s = (long)seedBytes[0] & 0xffL;
1104     for (int i = 1; i < 8; ++i)
1105     s = (s << 8) | ((long)seedBytes[i] & 0xffL);
1106     seeder.set(s);
1107     }
1108     }
1109 jsr166 1.1 }