ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java
Revision: 1.23
Committed: Mon Sep 16 11:40:51 2013 UTC (10 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.22: +26 -4 lines
Log Message:
Reinstate optional SecureRandom initialization

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