ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.42
Committed: Tue Apr 19 21:49:40 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.41: +1 -1 lines
Log Message:
new Double -> Double.valueOf

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