ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.33
Committed: Sun Jan 4 09:15:11 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.32: +17 -19 lines
Log Message:
standardize Unsafe mechanics; slightly smaller bytecode

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