ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.49
Committed: Sun Nov 13 03:36:50 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.48: +3 -4 lines
Log Message:
revise (uselessly inaccessible) next(int) method javadoc, implementation and tests

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.49 * low-order bits. Because this class has no subclasses, this
174     * method cannot be invoked or overriden.
175 dl 1.47 *
176     * @param bits random bits
177     * @return the next pseudorandom value from this random number
178     * generator's sequence
179     */
180 jsr166 1.1 protected int next(int bits) {
181 jsr166 1.49 return nextInt() >>> (32 - bits);
182 dl 1.19 }
183    
184     /**
185     * The form of nextLong used by LongStream Spliterators. If
186     * origin is greater than bound, acts as unbounded form of
187     * nextLong, else as bounded form.
188     *
189     * @param origin the least value, unless greater than bound
190     * @param bound the upper bound (exclusive), must not equal origin
191     * @return a pseudorandom value
192     */
193     final long internalNextLong(long origin, long bound) {
194     long r = mix64(nextSeed());
195     if (origin < bound) {
196     long n = bound - origin, m = n - 1;
197     if ((n & m) == 0L) // power of two
198     r = (r & m) + origin;
199     else if (n > 0L) { // reject over-represented candidates
200     for (long u = r >>> 1; // ensure nonnegative
201     u + m - (r = u % n) < 0L; // rejection check
202     u = mix64(nextSeed()) >>> 1) // retry
203     ;
204     r += origin;
205     }
206     else { // range not representable as long
207     while (r < origin || r >= bound)
208     r = mix64(nextSeed());
209     }
210     }
211     return r;
212     }
213    
214     /**
215     * The form of nextInt used by IntStream Spliterators.
216     * Exactly the same as long version, except for types.
217     *
218     * @param origin the least value, unless greater than bound
219     * @param bound the upper bound (exclusive), must not equal origin
220     * @return a pseudorandom value
221     */
222     final int internalNextInt(int origin, int bound) {
223     int r = mix32(nextSeed());
224     if (origin < bound) {
225     int n = bound - origin, m = n - 1;
226     if ((n & m) == 0)
227     r = (r & m) + origin;
228     else if (n > 0) {
229     for (int u = r >>> 1;
230     u + m - (r = u % n) < 0;
231     u = mix32(nextSeed()) >>> 1)
232     ;
233     r += origin;
234     }
235     else {
236     while (r < origin || r >= bound)
237     r = mix32(nextSeed());
238     }
239     }
240     return r;
241     }
242    
243     /**
244     * The form of nextDouble used by DoubleStream Spliterators.
245     *
246     * @param origin the least value, unless greater than bound
247     * @param bound the upper bound (exclusive), must not equal origin
248     * @return a pseudorandom value
249     */
250     final double internalNextDouble(double origin, double bound) {
251     double r = (nextLong() >>> 11) * DOUBLE_UNIT;
252     if (origin < bound) {
253     r = r * (bound - origin) + origin;
254     if (r >= bound) // correct for rounding
255     r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
256     }
257     return r;
258     }
259    
260     /**
261     * Returns a pseudorandom {@code int} value.
262     *
263     * @return a pseudorandom {@code int} value
264     */
265     public int nextInt() {
266     return mix32(nextSeed());
267     }
268    
269     /**
270     * Returns a pseudorandom {@code int} value between zero (inclusive)
271     * and the specified bound (exclusive).
272     *
273 dl 1.21 * @param bound the upper bound (exclusive). Must be positive.
274 dl 1.19 * @return a pseudorandom {@code int} value between zero
275     * (inclusive) and the bound (exclusive)
276 dl 1.20 * @throws IllegalArgumentException if {@code bound} is not positive
277 dl 1.19 */
278     public int nextInt(int bound) {
279     if (bound <= 0)
280 jsr166 1.35 throw new IllegalArgumentException(BAD_BOUND);
281 dl 1.19 int r = mix32(nextSeed());
282     int m = bound - 1;
283     if ((bound & m) == 0) // power of two
284     r &= m;
285     else { // reject over-represented candidates
286     for (int u = r >>> 1;
287     u + m - (r = u % bound) < 0;
288     u = mix32(nextSeed()) >>> 1)
289     ;
290     }
291     return r;
292 jsr166 1.1 }
293    
294     /**
295 dl 1.19 * Returns a pseudorandom {@code int} value between the specified
296     * origin (inclusive) and the specified bound (exclusive).
297 jsr166 1.1 *
298 dl 1.19 * @param origin the least value returned
299 jsr166 1.1 * @param bound the upper bound (exclusive)
300 dl 1.19 * @return a pseudorandom {@code int} value between the origin
301     * (inclusive) and the bound (exclusive)
302     * @throws IllegalArgumentException if {@code origin} is greater than
303     * or equal to {@code bound}
304     */
305     public int nextInt(int origin, int bound) {
306     if (origin >= bound)
307 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
308 dl 1.19 return internalNextInt(origin, bound);
309     }
310    
311     /**
312     * Returns a pseudorandom {@code long} value.
313     *
314     * @return a pseudorandom {@code long} value
315 jsr166 1.1 */
316 dl 1.19 public long nextLong() {
317     return mix64(nextSeed());
318 jsr166 1.1 }
319    
320     /**
321 dl 1.19 * Returns a pseudorandom {@code long} value between zero (inclusive)
322     * and the specified bound (exclusive).
323 jsr166 1.1 *
324 dl 1.21 * @param bound the upper bound (exclusive). Must be positive.
325 dl 1.19 * @return a pseudorandom {@code long} value between zero
326     * (inclusive) and the bound (exclusive)
327 dl 1.20 * @throws IllegalArgumentException if {@code bound} is not positive
328 dl 1.19 */
329     public long nextLong(long bound) {
330     if (bound <= 0)
331 jsr166 1.35 throw new IllegalArgumentException(BAD_BOUND);
332 dl 1.19 long r = mix64(nextSeed());
333     long m = bound - 1;
334     if ((bound & m) == 0L) // power of two
335     r &= m;
336     else { // reject over-represented candidates
337     for (long u = r >>> 1;
338     u + m - (r = u % bound) < 0L;
339     u = mix64(nextSeed()) >>> 1)
340     ;
341 jsr166 1.1 }
342 dl 1.19 return r;
343 jsr166 1.1 }
344    
345     /**
346 dl 1.19 * Returns a pseudorandom {@code long} value between the specified
347     * origin (inclusive) and the specified bound (exclusive).
348 jsr166 1.1 *
349 dl 1.19 * @param origin the least value returned
350 jsr166 1.1 * @param bound the upper bound (exclusive)
351 dl 1.19 * @return a pseudorandom {@code long} value between the origin
352     * (inclusive) and the bound (exclusive)
353     * @throws IllegalArgumentException if {@code origin} is greater than
354     * or equal to {@code bound}
355     */
356     public long nextLong(long origin, long bound) {
357     if (origin >= bound)
358 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
359 dl 1.19 return internalNextLong(origin, bound);
360     }
361    
362     /**
363     * Returns a pseudorandom {@code double} value between zero
364     * (inclusive) and one (exclusive).
365     *
366     * @return a pseudorandom {@code double} value between zero
367 dl 1.21 * (inclusive) and one (exclusive)
368 jsr166 1.1 */
369 dl 1.19 public double nextDouble() {
370     return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
371 jsr166 1.1 }
372    
373     /**
374 dl 1.19 * Returns a pseudorandom {@code double} value between 0.0
375     * (inclusive) and the specified bound (exclusive).
376 jsr166 1.1 *
377 dl 1.21 * @param bound the upper bound (exclusive). Must be positive.
378 dl 1.19 * @return a pseudorandom {@code double} value between zero
379     * (inclusive) and the bound (exclusive)
380 dl 1.20 * @throws IllegalArgumentException if {@code bound} is not positive
381 dl 1.19 */
382     public double nextDouble(double bound) {
383     if (!(bound > 0.0))
384 jsr166 1.35 throw new IllegalArgumentException(BAD_BOUND);
385 dl 1.19 double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
386 jsr166 1.27 return (result < bound) ? result : // correct for rounding
387 dl 1.19 Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
388     }
389    
390     /**
391     * Returns a pseudorandom {@code double} value between the specified
392     * origin (inclusive) and bound (exclusive).
393     *
394     * @param origin the least value returned
395 dl 1.21 * @param bound the upper bound (exclusive)
396 dl 1.19 * @return a pseudorandom {@code double} value between the origin
397     * (inclusive) and the bound (exclusive)
398     * @throws IllegalArgumentException if {@code origin} is greater than
399     * or equal to {@code bound}
400     */
401     public double nextDouble(double origin, double bound) {
402     if (!(origin < bound))
403 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
404 dl 1.19 return internalNextDouble(origin, bound);
405     }
406    
407     /**
408     * Returns a pseudorandom {@code boolean} value.
409     *
410     * @return a pseudorandom {@code boolean} value
411 jsr166 1.1 */
412 dl 1.19 public boolean nextBoolean() {
413     return mix32(nextSeed()) < 0;
414 jsr166 1.1 }
415    
416     /**
417 dl 1.19 * Returns a pseudorandom {@code float} value between zero
418     * (inclusive) and one (exclusive).
419 jsr166 1.1 *
420 dl 1.19 * @return a pseudorandom {@code float} value between zero
421 dl 1.21 * (inclusive) and one (exclusive)
422 dl 1.19 */
423     public float nextFloat() {
424     return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
425 jsr166 1.1 }
426    
427 dl 1.7 public double nextGaussian() {
428     // Use nextLocalGaussian instead of nextGaussian field
429     Double d = nextLocalGaussian.get();
430     if (d != null) {
431     nextLocalGaussian.set(null);
432     return d.doubleValue();
433     }
434     double v1, v2, s;
435     do {
436     v1 = 2 * nextDouble() - 1; // between -1 and 1
437     v2 = 2 * nextDouble() - 1; // between -1 and 1
438     s = v1 * v1 + v2 * v2;
439     } while (s >= 1 || s == 0);
440     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
441 jsr166 1.42 nextLocalGaussian.set(Double.valueOf(v2 * multiplier));
442 dl 1.7 return v1 * multiplier;
443     }
444    
445 dl 1.19 // stream methods, coded in a way intended to better isolate for
446     // maintenance purposes the small differences across forms.
447    
448     /**
449     * Returns a stream producing the given {@code streamSize} number of
450     * pseudorandom {@code int} values.
451     *
452     * @param streamSize the number of values to generate
453     * @return a stream of pseudorandom {@code int} values
454     * @throws IllegalArgumentException if {@code streamSize} is
455     * less than zero
456 dl 1.21 * @since 1.8
457 dl 1.19 */
458     public IntStream ints(long streamSize) {
459     if (streamSize < 0L)
460 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
461 dl 1.19 return StreamSupport.intStream
462     (new RandomIntsSpliterator
463     (0L, streamSize, Integer.MAX_VALUE, 0),
464     false);
465     }
466    
467     /**
468     * Returns an effectively unlimited stream of pseudorandom {@code int}
469     * values.
470     *
471     * @implNote This method is implemented to be equivalent to {@code
472     * ints(Long.MAX_VALUE)}.
473     *
474     * @return a stream of pseudorandom {@code int} values
475 dl 1.21 * @since 1.8
476 dl 1.19 */
477     public IntStream ints() {
478     return StreamSupport.intStream
479     (new RandomIntsSpliterator
480     (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
481     false);
482     }
483    
484     /**
485 dl 1.21 * Returns a stream producing the given {@code streamSize} number
486     * of pseudorandom {@code int} values, each conforming to the given
487     * origin (inclusive) and bound (exclusive).
488 dl 1.19 *
489     * @param streamSize the number of values to generate
490 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
491     * @param randomNumberBound the bound (exclusive) of each random value
492 dl 1.19 * @return a stream of pseudorandom {@code int} values,
493 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
494 dl 1.19 * @throws IllegalArgumentException if {@code streamSize} is
495     * less than zero, or {@code randomNumberOrigin}
496     * is greater than or equal to {@code randomNumberBound}
497 dl 1.21 * @since 1.8
498 dl 1.19 */
499     public IntStream ints(long streamSize, int randomNumberOrigin,
500     int randomNumberBound) {
501     if (streamSize < 0L)
502 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
503 dl 1.19 if (randomNumberOrigin >= randomNumberBound)
504 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
505 dl 1.19 return StreamSupport.intStream
506     (new RandomIntsSpliterator
507     (0L, streamSize, randomNumberOrigin, randomNumberBound),
508     false);
509     }
510    
511     /**
512     * Returns an effectively unlimited stream of pseudorandom {@code
513 dl 1.21 * int} values, each conforming to the given origin (inclusive) and bound
514     * (exclusive).
515 dl 1.19 *
516     * @implNote This method is implemented to be equivalent to {@code
517     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
518     *
519 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
520     * @param randomNumberBound the bound (exclusive) of each random value
521 dl 1.19 * @return a stream of pseudorandom {@code int} values,
522 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
523 dl 1.19 * @throws IllegalArgumentException if {@code randomNumberOrigin}
524     * is greater than or equal to {@code randomNumberBound}
525 dl 1.21 * @since 1.8
526 dl 1.19 */
527     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
528     if (randomNumberOrigin >= randomNumberBound)
529 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
530 dl 1.19 return StreamSupport.intStream
531     (new RandomIntsSpliterator
532     (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
533     false);
534     }
535    
536     /**
537     * Returns a stream producing the given {@code streamSize} number of
538     * pseudorandom {@code long} values.
539     *
540     * @param streamSize the number of values to generate
541     * @return a stream of pseudorandom {@code long} values
542     * @throws IllegalArgumentException if {@code streamSize} is
543     * less than zero
544 dl 1.21 * @since 1.8
545 dl 1.19 */
546     public LongStream longs(long streamSize) {
547     if (streamSize < 0L)
548 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
549 dl 1.19 return StreamSupport.longStream
550     (new RandomLongsSpliterator
551     (0L, streamSize, Long.MAX_VALUE, 0L),
552     false);
553     }
554    
555     /**
556     * Returns an effectively unlimited stream of pseudorandom {@code long}
557     * values.
558     *
559     * @implNote This method is implemented to be equivalent to {@code
560     * longs(Long.MAX_VALUE)}.
561     *
562     * @return a stream of pseudorandom {@code long} values
563 dl 1.21 * @since 1.8
564 dl 1.19 */
565     public LongStream longs() {
566     return StreamSupport.longStream
567     (new RandomLongsSpliterator
568     (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
569     false);
570     }
571    
572     /**
573     * Returns a stream producing the given {@code streamSize} number of
574 dl 1.21 * pseudorandom {@code long}, each conforming to the given origin
575     * (inclusive) and bound (exclusive).
576 dl 1.19 *
577     * @param streamSize the number of values to generate
578 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
579     * @param randomNumberBound the bound (exclusive) of each random value
580 dl 1.19 * @return a stream of pseudorandom {@code long} values,
581 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
582 dl 1.19 * @throws IllegalArgumentException if {@code streamSize} is
583     * less than zero, or {@code randomNumberOrigin}
584     * is greater than or equal to {@code randomNumberBound}
585 dl 1.21 * @since 1.8
586 dl 1.19 */
587     public LongStream longs(long streamSize, long randomNumberOrigin,
588     long randomNumberBound) {
589     if (streamSize < 0L)
590 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
591 dl 1.19 if (randomNumberOrigin >= randomNumberBound)
592 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
593 dl 1.19 return StreamSupport.longStream
594     (new RandomLongsSpliterator
595     (0L, streamSize, randomNumberOrigin, randomNumberBound),
596     false);
597     }
598    
599     /**
600     * Returns an effectively unlimited stream of pseudorandom {@code
601 dl 1.21 * long} values, each conforming to the given origin (inclusive) and bound
602     * (exclusive).
603 dl 1.19 *
604     * @implNote This method is implemented to be equivalent to {@code
605     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
606     *
607 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
608     * @param randomNumberBound the bound (exclusive) of each random value
609 dl 1.19 * @return a stream of pseudorandom {@code long} values,
610 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
611 dl 1.19 * @throws IllegalArgumentException if {@code randomNumberOrigin}
612     * is greater than or equal to {@code randomNumberBound}
613 dl 1.21 * @since 1.8
614 dl 1.19 */
615     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
616     if (randomNumberOrigin >= randomNumberBound)
617 jsr166 1.35 throw new IllegalArgumentException(BAD_RANGE);
618 dl 1.19 return StreamSupport.longStream
619     (new RandomLongsSpliterator
620     (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
621     false);
622     }
623    
624     /**
625     * Returns a stream producing the given {@code streamSize} number of
626     * pseudorandom {@code double} values, each between zero
627     * (inclusive) and one (exclusive).
628     *
629     * @param streamSize the number of values to generate
630     * @return a stream of {@code double} values
631     * @throws IllegalArgumentException if {@code streamSize} is
632     * less than zero
633 dl 1.21 * @since 1.8
634 dl 1.19 */
635     public DoubleStream doubles(long streamSize) {
636     if (streamSize < 0L)
637 jsr166 1.35 throw new IllegalArgumentException(BAD_SIZE);
638 dl 1.19 return StreamSupport.doubleStream
639     (new RandomDoublesSpliterator
640     (0L, streamSize, Double.MAX_VALUE, 0.0),
641     false);
642     }
643    
644     /**
645     * Returns an effectively unlimited stream of pseudorandom {@code
646     * double} values, each between zero (inclusive) and one
647     * (exclusive).
648     *
649     * @implNote This method is implemented to be equivalent to {@code
650     * doubles(Long.MAX_VALUE)}.
651     *
652     * @return a stream of pseudorandom {@code double} values
653 dl 1.21 * @since 1.8
654 dl 1.19 */
655     public DoubleStream doubles() {
656     return StreamSupport.doubleStream
657     (new RandomDoublesSpliterator
658     (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
659     false);
660     }
661    
662     /**
663     * Returns a stream producing the given {@code streamSize} number of
664 dl 1.21 * pseudorandom {@code double} values, each conforming to the given origin
665     * (inclusive) and bound (exclusive).
666 dl 1.19 *
667     * @param streamSize the number of values to generate
668 dl 1.21 * @param randomNumberOrigin the origin (inclusive) of each random value
669     * @param randomNumberBound the bound (exclusive) of each random value
670 dl 1.19 * @return a stream of pseudorandom {@code double} values,
671 dl 1.21 * each with the given origin (inclusive) and bound (exclusive)
672 dl 1.19 * @throws IllegalArgumentException if {@code streamSize} is
673 dl 1.21 * less than zero
674 dl 1.19 * @throws IllegalArgumentException if {@code randomNumberOrigin}
675     * 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     /**
960     * Returns a new group with the system ThreadGroup (the
961     * topmost, parent-less group) as parent. Uses Unsafe to
962     * traverse Thread.group and ThreadGroup.parent fields.
963     */
964     static final ThreadGroup createThreadGroup(String name) {
965     if (name == null)
966     throw new NullPointerException();
967     try {
968     long tg = U.objectFieldOffset
969     (Thread.class.getDeclaredField("group"));
970     long gp = U.objectFieldOffset
971     (ThreadGroup.class.getDeclaredField("parent"));
972     ThreadGroup group = (ThreadGroup)
973     U.getObject(Thread.currentThread(), tg);
974     while (group != null) {
975     ThreadGroup parent = (ThreadGroup)U.getObject(group, gp);
976     if (parent == null)
977     return new ThreadGroup(group, name);
978     group = parent;
979     }
980     } catch (ReflectiveOperationException e) {
981     throw new Error(e);
982     }
983     // fall through if null as cannot-happen safeguard
984     throw new Error("Cannot create ThreadGroup");
985     }
986 jsr166 1.45
987 jsr166 1.13 // Serialization support
988 dl 1.9
989 jsr166 1.1 private static final long serialVersionUID = -5851777807851030925L;
990 dl 1.7
991 dl 1.9 /**
992 jsr166 1.14 * @serialField rnd long
993     * seed for random computations
994     * @serialField initialized boolean
995     * always true
996     */
997     private static final ObjectStreamField[] serialPersistentFields = {
998 jsr166 1.31 new ObjectStreamField("rnd", long.class),
999     new ObjectStreamField("initialized", boolean.class),
1000 jsr166 1.14 };
1001    
1002     /**
1003     * Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
1004 jsr166 1.16 * @param s the stream
1005 jsr166 1.17 * @throws java.io.IOException if an I/O error occurs
1006 jsr166 1.14 */
1007 jsr166 1.16 private void writeObject(java.io.ObjectOutputStream s)
1008 jsr166 1.14 throws java.io.IOException {
1009    
1010 jsr166 1.16 java.io.ObjectOutputStream.PutField fields = s.putFields();
1011 jsr166 1.33 fields.put("rnd", U.getLong(Thread.currentThread(), SEED));
1012 jsr166 1.14 fields.put("initialized", true);
1013 jsr166 1.16 s.writeFields();
1014 jsr166 1.14 }
1015    
1016     /**
1017 dl 1.9 * Returns the {@link #current() current} thread's {@code ThreadLocalRandom}.
1018 jsr166 1.16 * @return the {@link #current() current} thread's {@code ThreadLocalRandom}
1019 dl 1.9 */
1020     private Object readResolve() {
1021     return current();
1022     }
1023    
1024 jsr166 1.41 // Static initialization
1025    
1026     /**
1027     * The seed increment.
1028     */
1029     private static final long GAMMA = 0x9e3779b97f4a7c15L;
1030    
1031     /**
1032     * The increment for generating probe values.
1033     */
1034     private static final int PROBE_INCREMENT = 0x9e3779b9;
1035    
1036     /**
1037     * The increment of seeder per new instance.
1038     */
1039     private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
1040    
1041     // Constants from SplittableRandom
1042     private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
1043     private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
1044    
1045     // IllegalArgumentException messages
1046     static final String BAD_BOUND = "bound must be positive";
1047     static final String BAD_RANGE = "bound must be greater than origin";
1048     static final String BAD_SIZE = "size must be non-negative";
1049    
1050 dl 1.7 // Unsafe mechanics
1051 jsr166 1.46 private static final Unsafe U = Unsafe.getUnsafe();
1052 dl 1.7 private static final long SEED;
1053     private static final long PROBE;
1054     private static final long SECONDARY;
1055 dl 1.44 private static final long THREADLOCALS;
1056     private static final long INHERITABLETHREADLOCALS;
1057     private static final long INHERITEDACCESSCONTROLCONTEXT;
1058 dl 1.7 static {
1059     try {
1060 jsr166 1.33 SEED = U.objectFieldOffset
1061     (Thread.class.getDeclaredField("threadLocalRandomSeed"));
1062     PROBE = U.objectFieldOffset
1063     (Thread.class.getDeclaredField("threadLocalRandomProbe"));
1064     SECONDARY = U.objectFieldOffset
1065     (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed"));
1066 dl 1.44 THREADLOCALS = U.objectFieldOffset
1067     (Thread.class.getDeclaredField("threadLocals"));
1068     INHERITABLETHREADLOCALS = U.objectFieldOffset
1069     (Thread.class.getDeclaredField("inheritableThreadLocals"));
1070     INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset
1071     (Thread.class.getDeclaredField("inheritedAccessControlContext"));
1072 jsr166 1.32 } catch (ReflectiveOperationException e) {
1073 dl 1.7 throw new Error(e);
1074     }
1075     }
1076 jsr166 1.41
1077     /** Rarely-used holder for the second of a pair of Gaussians */
1078     private static final ThreadLocal<Double> nextLocalGaussian =
1079     new ThreadLocal<>();
1080    
1081     /** Generates per-thread initialization/probe field */
1082     private static final AtomicInteger probeGenerator = new AtomicInteger();
1083    
1084     /** The common ThreadLocalRandom */
1085     static final ThreadLocalRandom instance = new ThreadLocalRandom();
1086    
1087     /**
1088     * The next seed for default constructors.
1089     */
1090     private static final AtomicLong seeder
1091     = new AtomicLong(mix64(System.currentTimeMillis()) ^
1092     mix64(System.nanoTime()));
1093    
1094     // at end of <clinit> to survive static initialization circularity
1095     static {
1096     if (java.security.AccessController.doPrivileged(
1097     new java.security.PrivilegedAction<Boolean>() {
1098     public Boolean run() {
1099     return Boolean.getBoolean("java.util.secureRandomSeed");
1100     }})) {
1101     byte[] seedBytes = java.security.SecureRandom.getSeed(8);
1102     long s = (long)seedBytes[0] & 0xffL;
1103     for (int i = 1; i < 8; ++i)
1104     s = (s << 8) | ((long)seedBytes[i] & 0xffL);
1105     seeder.set(s);
1106     }
1107     }
1108 jsr166 1.1 }