ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.36
Committed: Sat Sep 19 21:39:03 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.35: +1 -2 lines
Log Message:
whitespace

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