• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.util;
27 import java.io.*;
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.function.DoubleConsumer;
30 import java.util.function.IntConsumer;
31 import java.util.function.LongConsumer;
32 import java.util.stream.DoubleStream;
33 import java.util.stream.IntStream;
34 import java.util.stream.LongStream;
35 import java.util.stream.StreamSupport;
36 
37 import sun.misc.Unsafe;
38 
39 /**
40  * An instance of this class is used to generate a stream of
41  * pseudorandom numbers. The class uses a 48-bit seed, which is
42  * modified using a linear congruential formula. (See Donald Knuth,
43  * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
44  * <p>
45  * If two instances of {@code Random} are created with the same
46  * seed, and the same sequence of method calls is made for each, they
47  * will generate and return identical sequences of numbers. In order to
48  * guarantee this property, particular algorithms are specified for the
49  * class {@code Random}. Java implementations must use all the algorithms
50  * shown here for the class {@code Random}, for the sake of absolute
51  * portability of Java code. However, subclasses of class {@code Random}
52  * are permitted to use other algorithms, so long as they adhere to the
53  * general contracts for all the methods.
54  * <p>
55  * The algorithms implemented by class {@code Random} use a
56  * {@code protected} utility method that on each invocation can supply
57  * up to 32 pseudorandomly generated bits.
58  * <p>
59  * Many applications will find the method {@link Math#random} simpler to use.
60  *
61  * <p>Instances of {@code java.util.Random} are threadsafe.
62  * However, the concurrent use of the same {@code java.util.Random}
63  * instance across threads may encounter contention and consequent
64  * poor performance. Consider instead using
65  * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
66  * designs.
67  *
68  * <p>Instances of {@code java.util.Random} are not cryptographically
69  * secure.  Consider instead using {@link java.security.SecureRandom} to
70  * get a cryptographically secure pseudo-random number generator for use
71  * by security-sensitive applications.
72  *
73  * @author  Frank Yellin
74  * @since   1.0
75  */
76 public
77 class Random implements java.io.Serializable {
78     /** use serialVersionUID from JDK 1.1 for interoperability */
79     static final long serialVersionUID = 3905348978240129619L;
80 
81     /**
82      * The internal state associated with this pseudorandom number generator.
83      * (The specs for the methods in this class describe the ongoing
84      * computation of this value.)
85      */
86     private final AtomicLong seed;
87 
88     private static final long multiplier = 0x5DEECE66DL;
89     private static final long addend = 0xBL;
90     private static final long mask = (1L << 48) - 1;
91 
92     private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
93 
94     // IllegalArgumentException messages
95     static final String BadBound = "bound must be positive";
96     static final String BadRange = "bound must be greater than origin";
97     static final String BadSize  = "size must be non-negative";
98 
99     /**
100      * Creates a new random number generator. This constructor sets
101      * the seed of the random number generator to a value very likely
102      * to be distinct from any other invocation of this constructor.
103      */
Random()104     public Random() {
105         this(seedUniquifier() ^ System.nanoTime());
106     }
107 
seedUniquifier()108     private static long seedUniquifier() {
109         // L'Ecuyer, "Tables of Linear Congruential Generators of
110         // Different Sizes and Good Lattice Structure", 1999
111         for (;;) {
112             long current = seedUniquifier.get();
113             long next = current * 181783497276652981L;
114             if (seedUniquifier.compareAndSet(current, next))
115                 return next;
116         }
117     }
118 
119     private static final AtomicLong seedUniquifier
120         = new AtomicLong(8682522807148012L);
121 
122     /**
123      * Creates a new random number generator using a single {@code long} seed.
124      * The seed is the initial value of the internal state of the pseudorandom
125      * number generator which is maintained by method {@link #next}.
126      *
127      * <p>The invocation {@code new Random(seed)} is equivalent to:
128      *  <pre> {@code
129      * Random rnd = new Random();
130      * rnd.setSeed(seed);}</pre>
131      *
132      * @param seed the initial seed
133      * @see   #setSeed(long)
134      */
Random(long seed)135     public Random(long seed) {
136         if (getClass() == Random.class)
137             this.seed = new AtomicLong(initialScramble(seed));
138         else {
139             // subclass might have overriden setSeed
140             this.seed = new AtomicLong();
141             setSeed(seed);
142         }
143     }
144 
initialScramble(long seed)145     private static long initialScramble(long seed) {
146         return (seed ^ multiplier) & mask;
147     }
148 
149     /**
150      * Sets the seed of this random number generator using a single
151      * {@code long} seed. The general contract of {@code setSeed} is
152      * that it alters the state of this random number generator object
153      * so as to be in exactly the same state as if it had just been
154      * created with the argument {@code seed} as a seed. The method
155      * {@code setSeed} is implemented by class {@code Random} by
156      * atomically updating the seed to
157      *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
158      * and clearing the {@code haveNextNextGaussian} flag used by {@link
159      * #nextGaussian}.
160      *
161      * <p>The implementation of {@code setSeed} by class {@code Random}
162      * happens to use only 48 bits of the given seed. In general, however,
163      * an overriding method may use all 64 bits of the {@code long}
164      * argument as a seed value.
165      *
166      * @param seed the initial seed
167      */
setSeed(long seed)168     synchronized public void setSeed(long seed) {
169         this.seed.set(initialScramble(seed));
170         haveNextNextGaussian = false;
171     }
172 
173     /**
174      * Generates the next pseudorandom number. Subclasses should
175      * override this, as this is used by all other methods.
176      *
177      * <p>The general contract of {@code next} is that it returns an
178      * {@code int} value and if the argument {@code bits} is between
179      * {@code 1} and {@code 32} (inclusive), then that many low-order
180      * bits of the returned value will be (approximately) independently
181      * chosen bit values, each of which is (approximately) equally
182      * likely to be {@code 0} or {@code 1}. The method {@code next} is
183      * implemented by class {@code Random} by atomically updating the seed to
184      *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
185      * and returning
186      *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
187      *
188      * This is a linear congruential pseudorandom number generator, as
189      * defined by D. H. Lehmer and described by Donald E. Knuth in
190      * <i>The Art of Computer Programming,</i> Volume 3:
191      * <i>Seminumerical Algorithms</i>, section 3.2.1.
192      *
193      * @param  bits random bits
194      * @return the next pseudorandom value from this random number
195      *         generator's sequence
196      * @since  1.1
197      */
next(int bits)198     protected int next(int bits) {
199         long oldseed, nextseed;
200         AtomicLong seed = this.seed;
201         do {
202             oldseed = seed.get();
203             nextseed = (oldseed * multiplier + addend) & mask;
204         } while (!seed.compareAndSet(oldseed, nextseed));
205         return (int)(nextseed >>> (48 - bits));
206     }
207 
208     /**
209      * Generates random bytes and places them into a user-supplied
210      * byte array.  The number of random bytes produced is equal to
211      * the length of the byte array.
212      *
213      * <p>The method {@code nextBytes} is implemented by class {@code Random}
214      * as if by:
215      *  <pre> {@code
216      * public void nextBytes(byte[] bytes) {
217      *   for (int i = 0; i < bytes.length; )
218      *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
219      *          n-- > 0; rnd >>= 8)
220      *       bytes[i++] = (byte)rnd;
221      * }}</pre>
222      *
223      * @param  bytes the byte array to fill with random bytes
224      * @throws NullPointerException if the byte array is null
225      * @since  1.1
226      */
nextBytes(byte[] bytes)227     public void nextBytes(byte[] bytes) {
228         for (int i = 0, len = bytes.length; i < len; )
229             for (int rnd = nextInt(),
230                      n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
231                  n-- > 0; rnd >>= Byte.SIZE)
232                 bytes[i++] = (byte)rnd;
233     }
234 
235     /**
236      * The form of nextLong used by LongStream Spliterators.  If
237      * origin is greater than bound, acts as unbounded form of
238      * nextLong, else as bounded form.
239      *
240      * @param origin the least value, unless greater than bound
241      * @param bound the upper bound (exclusive), must not equal origin
242      * @return a pseudorandom value
243      */
internalNextLong(long origin, long bound)244     final long internalNextLong(long origin, long bound) {
245         long r = nextLong();
246         if (origin < bound) {
247             long n = bound - origin, m = n - 1;
248             if ((n & m) == 0L)  // power of two
249                 r = (r & m) + origin;
250             else if (n > 0L) {  // reject over-represented candidates
251                 for (long u = r >>> 1;            // ensure nonnegative
252                      u + m - (r = u % n) < 0L;    // rejection check
253                      u = nextLong() >>> 1) // retry
254                     ;
255                 r += origin;
256             }
257             else {              // range not representable as long
258                 while (r < origin || r >= bound)
259                     r = nextLong();
260             }
261         }
262         return r;
263     }
264 
265     /**
266      * The form of nextInt used by IntStream Spliterators.
267      * For the unbounded case: uses nextInt().
268      * For the bounded case with representable range: uses nextInt(int bound)
269      * For the bounded case with unrepresentable range: uses nextInt()
270      *
271      * @param origin the least value, unless greater than bound
272      * @param bound the upper bound (exclusive), must not equal origin
273      * @return a pseudorandom value
274      */
internalNextInt(int origin, int bound)275     final int internalNextInt(int origin, int bound) {
276         if (origin < bound) {
277             int n = bound - origin;
278             if (n > 0) {
279                 return nextInt(n) + origin;
280             }
281             else {  // range not representable as int
282                 int r;
283                 do {
284                     r = nextInt();
285                 } while (r < origin || r >= bound);
286                 return r;
287             }
288         }
289         else {
290             return nextInt();
291         }
292     }
293 
294     /**
295      * The form of nextDouble used by DoubleStream Spliterators.
296      *
297      * @param origin the least value, unless greater than bound
298      * @param bound the upper bound (exclusive), must not equal origin
299      * @return a pseudorandom value
300      */
internalNextDouble(double origin, double bound)301     final double internalNextDouble(double origin, double bound) {
302         double r = nextDouble();
303         if (origin < bound) {
304             r = r * (bound - origin) + origin;
305             if (r >= bound) // correct for rounding
306                 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
307         }
308         return r;
309     }
310 
311     /**
312      * Returns the next pseudorandom, uniformly distributed {@code int}
313      * value from this random number generator's sequence. The general
314      * contract of {@code nextInt} is that one {@code int} value is
315      * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
316      * </sup></font> possible {@code int} values are produced with
317      * (approximately) equal probability.
318      *
319      * <p>The method {@code nextInt} is implemented by class {@code Random}
320      * as if by:
321      *  <pre> {@code
322      * public int nextInt() {
323      *   return next(32);
324      * }}</pre>
325      *
326      * @return the next pseudorandom, uniformly distributed {@code int}
327      *         value from this random number generator's sequence
328      */
nextInt()329     public int nextInt() {
330         return next(32);
331     }
332 
333     /**
334      * Returns a pseudorandom, uniformly distributed {@code int} value
335      * between 0 (inclusive) and the specified value (exclusive), drawn from
336      * this random number generator's sequence.  The general contract of
337      * {@code nextInt} is that one {@code int} value in the specified range
338      * is pseudorandomly generated and returned.  All {@code n} possible
339      * {@code int} values are produced with (approximately) equal
340      * probability.  The method {@code nextInt(int n)} is implemented by
341      * class {@code Random} as if by:
342      *  <pre> {@code
343      * public int nextInt(int n) {
344      *   if (n <= 0)
345      *     throw new IllegalArgumentException("n must be positive");
346      *
347      *   if ((n & -n) == n)  // i.e., n is a power of 2
348      *     return (int)((n * (long)next(31)) >> 31);
349      *
350      *   int bits, val;
351      *   do {
352      *       bits = next(31);
353      *       val = bits % n;
354      *   } while (bits - val + (n-1) < 0);
355      *   return val;
356      * }}</pre>
357      *
358      * <p>The hedge "approximately" is used in the foregoing description only
359      * because the next method is only approximately an unbiased source of
360      * independently chosen bits.  If it were a perfect source of randomly
361      * chosen bits, then the algorithm shown would choose {@code int}
362      * values from the stated range with perfect uniformity.
363      * <p>
364      * The algorithm is slightly tricky.  It rejects values that would result
365      * in an uneven distribution (due to the fact that 2^31 is not divisible
366      * by n). The probability of a value being rejected depends on n.  The
367      * worst case is n=2^30+1, for which the probability of a reject is 1/2,
368      * and the expected number of iterations before the loop terminates is 2.
369      * <p>
370      * The algorithm treats the case where n is a power of two specially: it
371      * returns the correct number of high-order bits from the underlying
372      * pseudo-random number generator.  In the absence of special treatment,
373      * the correct number of <i>low-order</i> bits would be returned.  Linear
374      * congruential pseudo-random number generators such as the one
375      * implemented by this class are known to have short periods in the
376      * sequence of values of their low-order bits.  Thus, this special case
377      * greatly increases the length of the sequence of values returned by
378      * successive calls to this method if n is a small power of two.
379      *
380      * @param n the bound on the random number to be returned.  Must be
381      *        positive.
382      * @return the next pseudorandom, uniformly distributed {@code int}
383      *         value between {@code 0} (inclusive) and {@code n} (exclusive)
384      *         from this random number generator's sequence
385      * @throws IllegalArgumentException if n is not positive
386      * @since 1.2
387      */
388 
nextInt(int n)389     public int nextInt(int n) {
390         if (n <= 0)
391             throw new IllegalArgumentException("n must be positive");
392 
393         if ((n & -n) == n)  // i.e., n is a power of 2
394             return (int)((n * (long)next(31)) >> 31);
395 
396         int bits, val;
397         do {
398             bits = next(31);
399             val = bits % n;
400         } while (bits - val + (n-1) < 0);
401         return val;
402     }
403 
404     /**
405      * Returns the next pseudorandom, uniformly distributed {@code long}
406      * value from this random number generator's sequence. The general
407      * contract of {@code nextLong} is that one {@code long} value is
408      * pseudorandomly generated and returned.
409      *
410      * <p>The method {@code nextLong} is implemented by class {@code Random}
411      * as if by:
412      *  <pre> {@code
413      * public long nextLong() {
414      *   return ((long)next(32) << 32) + next(32);
415      * }}</pre>
416      *
417      * Because class {@code Random} uses a seed with only 48 bits,
418      * this algorithm will not return all possible {@code long} values.
419      *
420      * @return the next pseudorandom, uniformly distributed {@code long}
421      *         value from this random number generator's sequence
422      */
nextLong()423     public long nextLong() {
424         // it's okay that the bottom word remains signed.
425         return ((long)(next(32)) << 32) + next(32);
426     }
427 
428     /**
429      * Returns the next pseudorandom, uniformly distributed
430      * {@code boolean} value from this random number generator's
431      * sequence. The general contract of {@code nextBoolean} is that one
432      * {@code boolean} value is pseudorandomly generated and returned.  The
433      * values {@code true} and {@code false} are produced with
434      * (approximately) equal probability.
435      *
436      * <p>The method {@code nextBoolean} is implemented by class {@code Random}
437      * as if by:
438      *  <pre> {@code
439      * public boolean nextBoolean() {
440      *   return next(1) != 0;
441      * }}</pre>
442      *
443      * @return the next pseudorandom, uniformly distributed
444      *         {@code boolean} value from this random number generator's
445      *         sequence
446      * @since 1.2
447      */
nextBoolean()448     public boolean nextBoolean() {
449         return next(1) != 0;
450     }
451 
452     /**
453      * Returns the next pseudorandom, uniformly distributed {@code float}
454      * value between {@code 0.0} and {@code 1.0} from this random
455      * number generator's sequence.
456      *
457      * <p>The general contract of {@code nextFloat} is that one
458      * {@code float} value, chosen (approximately) uniformly from the
459      * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
460      * pseudorandomly generated and returned. All 2<font
461      * size="-1"><sup>24</sup></font> possible {@code float} values
462      * of the form <i>m&nbsp;x&nbsp</i>2<font
463      * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
464      * integer less than 2<font size="-1"><sup>24</sup> </font>, are
465      * produced with (approximately) equal probability.
466      *
467      * <p>The method {@code nextFloat} is implemented by class {@code Random}
468      * as if by:
469      *  <pre> {@code
470      * public float nextFloat() {
471      *   return next(24) / ((float)(1 << 24));
472      * }}</pre>
473      *
474      * <p>The hedge "approximately" is used in the foregoing description only
475      * because the next method is only approximately an unbiased source of
476      * independently chosen bits. If it were a perfect source of randomly
477      * chosen bits, then the algorithm shown would choose {@code float}
478      * values from the stated range with perfect uniformity.<p>
479      * [In early versions of Java, the result was incorrectly calculated as:
480      *  <pre> {@code
481      *   return next(30) / ((float)(1 << 30));}</pre>
482      * This might seem to be equivalent, if not better, but in fact it
483      * introduced a slight nonuniformity because of the bias in the rounding
484      * of floating-point numbers: it was slightly more likely that the
485      * low-order bit of the significand would be 0 than that it would be 1.]
486      *
487      * @return the next pseudorandom, uniformly distributed {@code float}
488      *         value between {@code 0.0} and {@code 1.0} from this
489      *         random number generator's sequence
490      */
nextFloat()491     public float nextFloat() {
492         return next(24) / ((float)(1 << 24));
493     }
494 
495     /**
496      * Returns the next pseudorandom, uniformly distributed
497      * {@code double} value between {@code 0.0} and
498      * {@code 1.0} from this random number generator's sequence.
499      *
500      * <p>The general contract of {@code nextDouble} is that one
501      * {@code double} value, chosen (approximately) uniformly from the
502      * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
503      * pseudorandomly generated and returned.
504      *
505      * <p>The method {@code nextDouble} is implemented by class {@code Random}
506      * as if by:
507      *  <pre> {@code
508      * public double nextDouble() {
509      *   return (((long)next(26) << 27) + next(27))
510      *     / (double)(1L << 53);
511      * }}</pre>
512      *
513      * <p>The hedge "approximately" is used in the foregoing description only
514      * because the {@code next} method is only approximately an unbiased
515      * source of independently chosen bits. If it were a perfect source of
516      * randomly chosen bits, then the algorithm shown would choose
517      * {@code double} values from the stated range with perfect uniformity.
518      * <p>[In early versions of Java, the result was incorrectly calculated as:
519      *  <pre> {@code
520      *   return (((long)next(27) << 27) + next(27))
521      *     / (double)(1L << 54);}</pre>
522      * This might seem to be equivalent, if not better, but in fact it
523      * introduced a large nonuniformity because of the bias in the rounding
524      * of floating-point numbers: it was three times as likely that the
525      * low-order bit of the significand would be 0 than that it would be 1!
526      * This nonuniformity probably doesn't matter much in practice, but we
527      * strive for perfection.]
528      *
529      * @return the next pseudorandom, uniformly distributed {@code double}
530      *         value between {@code 0.0} and {@code 1.0} from this
531      *         random number generator's sequence
532      * @see Math#random
533      */
nextDouble()534     public double nextDouble() {
535         return (((long)(next(26)) << 27) + next(27))
536             / (double)(1L << 53);
537     }
538 
539     private double nextNextGaussian;
540     private boolean haveNextNextGaussian = false;
541 
542     /**
543      * Returns the next pseudorandom, Gaussian ("normally") distributed
544      * {@code double} value with mean {@code 0.0} and standard
545      * deviation {@code 1.0} from this random number generator's sequence.
546      * <p>
547      * The general contract of {@code nextGaussian} is that one
548      * {@code double} value, chosen from (approximately) the usual
549      * normal distribution with mean {@code 0.0} and standard deviation
550      * {@code 1.0}, is pseudorandomly generated and returned.
551      *
552      * <p>The method {@code nextGaussian} is implemented by class
553      * {@code Random} as if by a threadsafe version of the following:
554      *  <pre> {@code
555      * private double nextNextGaussian;
556      * private boolean haveNextNextGaussian = false;
557      *
558      * public double nextGaussian() {
559      *   if (haveNextNextGaussian) {
560      *     haveNextNextGaussian = false;
561      *     return nextNextGaussian;
562      *   } else {
563      *     double v1, v2, s;
564      *     do {
565      *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
566      *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
567      *       s = v1 * v1 + v2 * v2;
568      *     } while (s >= 1 || s == 0);
569      *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
570      *     nextNextGaussian = v2 * multiplier;
571      *     haveNextNextGaussian = true;
572      *     return v1 * multiplier;
573      *   }
574      * }}</pre>
575      * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
576      * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
577      * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
578      * section 3.4.1, subsection C, algorithm P. Note that it generates two
579      * independent values at the cost of only one call to {@code StrictMath.log}
580      * and one call to {@code StrictMath.sqrt}.
581      *
582      * @return the next pseudorandom, Gaussian ("normally") distributed
583      *         {@code double} value with mean {@code 0.0} and
584      *         standard deviation {@code 1.0} from this random number
585      *         generator's sequence
586      */
nextGaussian()587     synchronized public double nextGaussian() {
588         // See Knuth, ACP, Section 3.4.1 Algorithm C.
589         if (haveNextNextGaussian) {
590             haveNextNextGaussian = false;
591             return nextNextGaussian;
592         } else {
593             double v1, v2, s;
594             do {
595                 v1 = 2 * nextDouble() - 1; // between -1 and 1
596                 v2 = 2 * nextDouble() - 1; // between -1 and 1
597                 s = v1 * v1 + v2 * v2;
598             } while (s >= 1 || s == 0);
599             double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
600             nextNextGaussian = v2 * multiplier;
601             haveNextNextGaussian = true;
602             return v1 * multiplier;
603         }
604     }
605 
606     // stream methods, coded in a way intended to better isolate for
607     // maintenance purposes the small differences across forms.
608 
609     /**
610      * Returns a stream producing the given {@code streamSize} number of
611      * pseudorandom {@code int} values.
612      *
613      * <p>A pseudorandom {@code int} value is generated as if it's the result of
614      * calling the method {@link #nextInt()}.
615      *
616      * @param streamSize the number of values to generate
617      * @return a stream of pseudorandom {@code int} values
618      * @throws IllegalArgumentException if {@code streamSize} is
619      *         less than zero
620      * @since 1.8
621      */
ints(long streamSize)622     public IntStream ints(long streamSize) {
623         if (streamSize < 0L)
624             throw new IllegalArgumentException(BadSize);
625         return StreamSupport.intStream
626                 (new RandomIntsSpliterator
627                          (this, 0L, streamSize, Integer.MAX_VALUE, 0),
628                  false);
629     }
630 
631     /**
632      * Returns an effectively unlimited stream of pseudorandom {@code int}
633      * values.
634      *
635      * <p>A pseudorandom {@code int} value is generated as if it's the result of
636      * calling the method {@link #nextInt()}.
637      *
638      * @implNote This method is implemented to be equivalent to {@code
639      * ints(Long.MAX_VALUE)}.
640      *
641      * @return a stream of pseudorandom {@code int} values
642      * @since 1.8
643      */
ints()644     public IntStream ints() {
645         return StreamSupport.intStream
646                 (new RandomIntsSpliterator
647                          (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
648                  false);
649     }
650 
651     /**
652      * Returns a stream producing the given {@code streamSize} number
653      * of pseudorandom {@code int} values, each conforming to the given
654      * origin (inclusive) and bound (exclusive).
655      *
656      * <p>A pseudorandom {@code int} value is generated as if it's the result of
657      * calling the following method with the origin and bound:
658      * <pre> {@code
659      * int nextInt(int origin, int bound) {
660      *   int n = bound - origin;
661      *   if (n > 0) {
662      *     return nextInt(n) + origin;
663      *   }
664      *   else {  // range not representable as int
665      *     int r;
666      *     do {
667      *       r = nextInt();
668      *     } while (r < origin || r >= bound);
669      *     return r;
670      *   }
671      * }}</pre>
672      *
673      * @param streamSize the number of values to generate
674      * @param randomNumberOrigin the origin (inclusive) of each random value
675      * @param randomNumberBound the bound (exclusive) of each random value
676      * @return a stream of pseudorandom {@code int} values,
677      *         each with the given origin (inclusive) and bound (exclusive)
678      * @throws IllegalArgumentException if {@code streamSize} is
679      *         less than zero, or {@code randomNumberOrigin}
680      *         is greater than or equal to {@code randomNumberBound}
681      * @since 1.8
682      */
ints(long streamSize, int randomNumberOrigin, int randomNumberBound)683     public IntStream ints(long streamSize, int randomNumberOrigin,
684                           int randomNumberBound) {
685         if (streamSize < 0L)
686             throw new IllegalArgumentException(BadSize);
687         if (randomNumberOrigin >= randomNumberBound)
688             throw new IllegalArgumentException(BadRange);
689         return StreamSupport.intStream
690                 (new RandomIntsSpliterator
691                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
692                  false);
693     }
694 
695     /**
696      * Returns an effectively unlimited stream of pseudorandom {@code
697      * int} values, each conforming to the given origin (inclusive) and bound
698      * (exclusive).
699      *
700      * <p>A pseudorandom {@code int} value is generated as if it's the result of
701      * calling the following method with the origin and bound:
702      * <pre> {@code
703      * int nextInt(int origin, int bound) {
704      *   int n = bound - origin;
705      *   if (n > 0) {
706      *     return nextInt(n) + origin;
707      *   }
708      *   else {  // range not representable as int
709      *     int r;
710      *     do {
711      *       r = nextInt();
712      *     } while (r < origin || r >= bound);
713      *     return r;
714      *   }
715      * }}</pre>
716      *
717      * @implNote This method is implemented to be equivalent to {@code
718      * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
719      *
720      * @param randomNumberOrigin the origin (inclusive) of each random value
721      * @param randomNumberBound the bound (exclusive) of each random value
722      * @return a stream of pseudorandom {@code int} values,
723      *         each with the given origin (inclusive) and bound (exclusive)
724      * @throws IllegalArgumentException if {@code randomNumberOrigin}
725      *         is greater than or equal to {@code randomNumberBound}
726      * @since 1.8
727      */
ints(int randomNumberOrigin, int randomNumberBound)728     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
729         if (randomNumberOrigin >= randomNumberBound)
730             throw new IllegalArgumentException(BadRange);
731         return StreamSupport.intStream
732                 (new RandomIntsSpliterator
733                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
734                  false);
735     }
736 
737     /**
738      * Returns a stream producing the given {@code streamSize} number of
739      * pseudorandom {@code long} values.
740      *
741      * <p>A pseudorandom {@code long} value is generated as if it's the result
742      * of calling the method {@link #nextLong()}.
743      *
744      * @param streamSize the number of values to generate
745      * @return a stream of pseudorandom {@code long} values
746      * @throws IllegalArgumentException if {@code streamSize} is
747      *         less than zero
748      * @since 1.8
749      */
longs(long streamSize)750     public LongStream longs(long streamSize) {
751         if (streamSize < 0L)
752             throw new IllegalArgumentException(BadSize);
753         return StreamSupport.longStream
754                 (new RandomLongsSpliterator
755                          (this, 0L, streamSize, Long.MAX_VALUE, 0L),
756                  false);
757     }
758 
759     /**
760      * Returns an effectively unlimited stream of pseudorandom {@code long}
761      * values.
762      *
763      * <p>A pseudorandom {@code long} value is generated as if it's the result
764      * of calling the method {@link #nextLong()}.
765      *
766      * @implNote This method is implemented to be equivalent to {@code
767      * longs(Long.MAX_VALUE)}.
768      *
769      * @return a stream of pseudorandom {@code long} values
770      * @since 1.8
771      */
longs()772     public LongStream longs() {
773         return StreamSupport.longStream
774                 (new RandomLongsSpliterator
775                          (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
776                  false);
777     }
778 
779     /**
780      * Returns a stream producing the given {@code streamSize} number of
781      * pseudorandom {@code long}, each conforming to the given origin
782      * (inclusive) and bound (exclusive).
783      *
784      * <p>A pseudorandom {@code long} value is generated as if it's the result
785      * of calling the following method with the origin and bound:
786      * <pre> {@code
787      * long nextLong(long origin, long bound) {
788      *   long r = nextLong();
789      *   long n = bound - origin, m = n - 1;
790      *   if ((n & m) == 0L)  // power of two
791      *     r = (r & m) + origin;
792      *   else if (n > 0L) {  // reject over-represented candidates
793      *     for (long u = r >>> 1;            // ensure nonnegative
794      *          u + m - (r = u % n) < 0L;    // rejection check
795      *          u = nextLong() >>> 1) // retry
796      *         ;
797      *     r += origin;
798      *   }
799      *   else {              // range not representable as long
800      *     while (r < origin || r >= bound)
801      *       r = nextLong();
802      *   }
803      *   return r;
804      * }}</pre>
805      *
806      * @param streamSize the number of values to generate
807      * @param randomNumberOrigin the origin (inclusive) of each random value
808      * @param randomNumberBound the bound (exclusive) of each random value
809      * @return a stream of pseudorandom {@code long} values,
810      *         each with the given origin (inclusive) and bound (exclusive)
811      * @throws IllegalArgumentException if {@code streamSize} is
812      *         less than zero, or {@code randomNumberOrigin}
813      *         is greater than or equal to {@code randomNumberBound}
814      * @since 1.8
815      */
longs(long streamSize, long randomNumberOrigin, long randomNumberBound)816     public LongStream longs(long streamSize, long randomNumberOrigin,
817                             long randomNumberBound) {
818         if (streamSize < 0L)
819             throw new IllegalArgumentException(BadSize);
820         if (randomNumberOrigin >= randomNumberBound)
821             throw new IllegalArgumentException(BadRange);
822         return StreamSupport.longStream
823                 (new RandomLongsSpliterator
824                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
825                  false);
826     }
827 
828     /**
829      * Returns an effectively unlimited stream of pseudorandom {@code
830      * long} values, each conforming to the given origin (inclusive) and bound
831      * (exclusive).
832      *
833      * <p>A pseudorandom {@code long} value is generated as if it's the result
834      * of calling the following method with the origin and bound:
835      * <pre> {@code
836      * long nextLong(long origin, long bound) {
837      *   long r = nextLong();
838      *   long n = bound - origin, m = n - 1;
839      *   if ((n & m) == 0L)  // power of two
840      *     r = (r & m) + origin;
841      *   else if (n > 0L) {  // reject over-represented candidates
842      *     for (long u = r >>> 1;            // ensure nonnegative
843      *          u + m - (r = u % n) < 0L;    // rejection check
844      *          u = nextLong() >>> 1) // retry
845      *         ;
846      *     r += origin;
847      *   }
848      *   else {              // range not representable as long
849      *     while (r < origin || r >= bound)
850      *       r = nextLong();
851      *   }
852      *   return r;
853      * }}</pre>
854      *
855      * @implNote This method is implemented to be equivalent to {@code
856      * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
857      *
858      * @param randomNumberOrigin the origin (inclusive) of each random value
859      * @param randomNumberBound the bound (exclusive) of each random value
860      * @return a stream of pseudorandom {@code long} values,
861      *         each with the given origin (inclusive) and bound (exclusive)
862      * @throws IllegalArgumentException if {@code randomNumberOrigin}
863      *         is greater than or equal to {@code randomNumberBound}
864      * @since 1.8
865      */
longs(long randomNumberOrigin, long randomNumberBound)866     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
867         if (randomNumberOrigin >= randomNumberBound)
868             throw new IllegalArgumentException(BadRange);
869         return StreamSupport.longStream
870                 (new RandomLongsSpliterator
871                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
872                  false);
873     }
874 
875     /**
876      * Returns a stream producing the given {@code streamSize} number of
877      * pseudorandom {@code double} values, each between zero
878      * (inclusive) and one (exclusive).
879      *
880      * <p>A pseudorandom {@code double} value is generated as if it's the result
881      * of calling the method {@link #nextDouble()}.
882      *
883      * @param streamSize the number of values to generate
884      * @return a stream of {@code double} values
885      * @throws IllegalArgumentException if {@code streamSize} is
886      *         less than zero
887      * @since 1.8
888      */
doubles(long streamSize)889     public DoubleStream doubles(long streamSize) {
890         if (streamSize < 0L)
891             throw new IllegalArgumentException(BadSize);
892         return StreamSupport.doubleStream
893                 (new RandomDoublesSpliterator
894                          (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
895                  false);
896     }
897 
898     /**
899      * Returns an effectively unlimited stream of pseudorandom {@code
900      * double} values, each between zero (inclusive) and one
901      * (exclusive).
902      *
903      * <p>A pseudorandom {@code double} value is generated as if it's the result
904      * of calling the method {@link #nextDouble()}.
905      *
906      * @implNote This method is implemented to be equivalent to {@code
907      * doubles(Long.MAX_VALUE)}.
908      *
909      * @return a stream of pseudorandom {@code double} values
910      * @since 1.8
911      */
doubles()912     public DoubleStream doubles() {
913         return StreamSupport.doubleStream
914                 (new RandomDoublesSpliterator
915                          (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
916                  false);
917     }
918 
919     /**
920      * Returns a stream producing the given {@code streamSize} number of
921      * pseudorandom {@code double} values, each conforming to the given origin
922      * (inclusive) and bound (exclusive).
923      *
924      * <p>A pseudorandom {@code double} value is generated as if it's the result
925      * of calling the following method with the origin and bound:
926      * <pre> {@code
927      * double nextDouble(double origin, double bound) {
928      *   double r = nextDouble();
929      *   r = r * (bound - origin) + origin;
930      *   if (r >= bound) // correct for rounding
931      *     r = Math.nextDown(bound);
932      *   return r;
933      * }}</pre>
934      *
935      * @param streamSize the number of values to generate
936      * @param randomNumberOrigin the origin (inclusive) of each random value
937      * @param randomNumberBound the bound (exclusive) of each random value
938      * @return a stream of pseudorandom {@code double} values,
939      *         each with the given origin (inclusive) and bound (exclusive)
940      * @throws IllegalArgumentException if {@code streamSize} is
941      *         less than zero
942      * @throws IllegalArgumentException if {@code randomNumberOrigin}
943      *         is greater than or equal to {@code randomNumberBound}
944      * @since 1.8
945      */
doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)946     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
947                                 double randomNumberBound) {
948         if (streamSize < 0L)
949             throw new IllegalArgumentException(BadSize);
950         if (!(randomNumberOrigin < randomNumberBound))
951             throw new IllegalArgumentException(BadRange);
952         return StreamSupport.doubleStream
953                 (new RandomDoublesSpliterator
954                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
955                  false);
956     }
957 
958     /**
959      * Returns an effectively unlimited stream of pseudorandom {@code
960      * double} values, each conforming to the given origin (inclusive) and bound
961      * (exclusive).
962      *
963      * <p>A pseudorandom {@code double} value is generated as if it's the result
964      * of calling the following method with the origin and bound:
965      * <pre> {@code
966      * double nextDouble(double origin, double bound) {
967      *   double r = nextDouble();
968      *   r = r * (bound - origin) + origin;
969      *   if (r >= bound) // correct for rounding
970      *     r = Math.nextDown(bound);
971      *   return r;
972      * }}</pre>
973      *
974      * @implNote This method is implemented to be equivalent to {@code
975      * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
976      *
977      * @param randomNumberOrigin the origin (inclusive) of each random value
978      * @param randomNumberBound the bound (exclusive) of each random value
979      * @return a stream of pseudorandom {@code double} values,
980      *         each with the given origin (inclusive) and bound (exclusive)
981      * @throws IllegalArgumentException if {@code randomNumberOrigin}
982      *         is greater than or equal to {@code randomNumberBound}
983      * @since 1.8
984      */
doubles(double randomNumberOrigin, double randomNumberBound)985     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
986         if (!(randomNumberOrigin < randomNumberBound))
987             throw new IllegalArgumentException(BadRange);
988         return StreamSupport.doubleStream
989                 (new RandomDoublesSpliterator
990                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
991                  false);
992     }
993 
994     /**
995      * Spliterator for int streams.  We multiplex the four int
996      * versions into one class by treating a bound less than origin as
997      * unbounded, and also by treating "infinite" as equivalent to
998      * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
999      * approach. The long and double versions of this class are
1000      * identical except for types.
1001      */
1002     static final class RandomIntsSpliterator implements Spliterator.OfInt {
1003         final Random rng;
1004         long index;
1005         final long fence;
1006         final int origin;
1007         final int bound;
RandomIntsSpliterator(Random rng, long index, long fence, int origin, int bound)1008         RandomIntsSpliterator(Random rng, long index, long fence,
1009                               int origin, int bound) {
1010             this.rng = rng; this.index = index; this.fence = fence;
1011             this.origin = origin; this.bound = bound;
1012         }
1013 
trySplit()1014         public RandomIntsSpliterator trySplit() {
1015             long i = index, m = (i + fence) >>> 1;
1016             return (m <= i) ? null :
1017                    new RandomIntsSpliterator(rng, i, index = m, origin, bound);
1018         }
1019 
estimateSize()1020         public long estimateSize() {
1021             return fence - index;
1022         }
1023 
characteristics()1024         public int characteristics() {
1025             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1026                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1027         }
1028 
tryAdvance(IntConsumer consumer)1029         public boolean tryAdvance(IntConsumer consumer) {
1030             if (consumer == null) throw new NullPointerException();
1031             long i = index, f = fence;
1032             if (i < f) {
1033                 consumer.accept(rng.internalNextInt(origin, bound));
1034                 index = i + 1;
1035                 return true;
1036             }
1037             return false;
1038         }
1039 
forEachRemaining(IntConsumer consumer)1040         public void forEachRemaining(IntConsumer consumer) {
1041             if (consumer == null) throw new NullPointerException();
1042             long i = index, f = fence;
1043             if (i < f) {
1044                 index = f;
1045                 Random r = rng;
1046                 int o = origin, b = bound;
1047                 do {
1048                     consumer.accept(r.internalNextInt(o, b));
1049                 } while (++i < f);
1050             }
1051         }
1052     }
1053 
1054     /**
1055      * Spliterator for long streams.
1056      */
1057     static final class RandomLongsSpliterator implements Spliterator.OfLong {
1058         final Random rng;
1059         long index;
1060         final long fence;
1061         final long origin;
1062         final long bound;
RandomLongsSpliterator(Random rng, long index, long fence, long origin, long bound)1063         RandomLongsSpliterator(Random rng, long index, long fence,
1064                                long origin, long bound) {
1065             this.rng = rng; this.index = index; this.fence = fence;
1066             this.origin = origin; this.bound = bound;
1067         }
1068 
trySplit()1069         public RandomLongsSpliterator trySplit() {
1070             long i = index, m = (i + fence) >>> 1;
1071             return (m <= i) ? null :
1072                    new RandomLongsSpliterator(rng, i, index = m, origin, bound);
1073         }
1074 
estimateSize()1075         public long estimateSize() {
1076             return fence - index;
1077         }
1078 
characteristics()1079         public int characteristics() {
1080             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1081                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1082         }
1083 
tryAdvance(LongConsumer consumer)1084         public boolean tryAdvance(LongConsumer consumer) {
1085             if (consumer == null) throw new NullPointerException();
1086             long i = index, f = fence;
1087             if (i < f) {
1088                 consumer.accept(rng.internalNextLong(origin, bound));
1089                 index = i + 1;
1090                 return true;
1091             }
1092             return false;
1093         }
1094 
forEachRemaining(LongConsumer consumer)1095         public void forEachRemaining(LongConsumer consumer) {
1096             if (consumer == null) throw new NullPointerException();
1097             long i = index, f = fence;
1098             if (i < f) {
1099                 index = f;
1100                 Random r = rng;
1101                 long o = origin, b = bound;
1102                 do {
1103                     consumer.accept(r.internalNextLong(o, b));
1104                 } while (++i < f);
1105             }
1106         }
1107 
1108     }
1109 
1110     /**
1111      * Spliterator for double streams.
1112      */
1113     static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
1114         final Random rng;
1115         long index;
1116         final long fence;
1117         final double origin;
1118         final double bound;
RandomDoublesSpliterator(Random rng, long index, long fence, double origin, double bound)1119         RandomDoublesSpliterator(Random rng, long index, long fence,
1120                                  double origin, double bound) {
1121             this.rng = rng; this.index = index; this.fence = fence;
1122             this.origin = origin; this.bound = bound;
1123         }
1124 
trySplit()1125         public RandomDoublesSpliterator trySplit() {
1126             long i = index, m = (i + fence) >>> 1;
1127             return (m <= i) ? null :
1128                    new RandomDoublesSpliterator(rng, i, index = m, origin, bound);
1129         }
1130 
estimateSize()1131         public long estimateSize() {
1132             return fence - index;
1133         }
1134 
characteristics()1135         public int characteristics() {
1136             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1137                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1138         }
1139 
tryAdvance(DoubleConsumer consumer)1140         public boolean tryAdvance(DoubleConsumer consumer) {
1141             if (consumer == null) throw new NullPointerException();
1142             long i = index, f = fence;
1143             if (i < f) {
1144                 consumer.accept(rng.internalNextDouble(origin, bound));
1145                 index = i + 1;
1146                 return true;
1147             }
1148             return false;
1149         }
1150 
forEachRemaining(DoubleConsumer consumer)1151         public void forEachRemaining(DoubleConsumer consumer) {
1152             if (consumer == null) throw new NullPointerException();
1153             long i = index, f = fence;
1154             if (i < f) {
1155                 index = f;
1156                 Random r = rng;
1157                 double o = origin, b = bound;
1158                 do {
1159                     consumer.accept(r.internalNextDouble(o, b));
1160                 } while (++i < f);
1161             }
1162         }
1163     }
1164 
1165     /**
1166      * Serializable fields for Random.
1167      *
1168      * @serialField    seed long
1169      *              seed for random computations
1170      * @serialField    nextNextGaussian double
1171      *              next Gaussian to be returned
1172      * @serialField      haveNextNextGaussian boolean
1173      *              nextNextGaussian is valid
1174      */
1175     private static final ObjectStreamField[] serialPersistentFields = {
1176         new ObjectStreamField("seed", Long.TYPE),
1177         new ObjectStreamField("nextNextGaussian", Double.TYPE),
1178         new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
1179     };
1180 
1181     /**
1182      * Reconstitute the {@code Random} instance from a stream (that is,
1183      * deserialize it).
1184      */
readObject(java.io.ObjectInputStream s)1185     private void readObject(java.io.ObjectInputStream s)
1186         throws java.io.IOException, ClassNotFoundException {
1187 
1188         ObjectInputStream.GetField fields = s.readFields();
1189 
1190         // The seed is read in as {@code long} for
1191         // historical reasons, but it is converted to an AtomicLong.
1192         long seedVal = fields.get("seed", -1L);
1193         if (seedVal < 0)
1194           throw new java.io.StreamCorruptedException(
1195                               "Random: invalid seed");
1196         resetSeed(seedVal);
1197         nextNextGaussian = fields.get("nextNextGaussian", 0.0);
1198         haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
1199     }
1200 
1201     /**
1202      * Save the {@code Random} instance to a stream.
1203      */
writeObject(ObjectOutputStream s)1204     synchronized private void writeObject(ObjectOutputStream s)
1205         throws IOException {
1206 
1207         // set the values of the Serializable fields
1208         ObjectOutputStream.PutField fields = s.putFields();
1209 
1210         // The seed is serialized as a long for historical reasons.
1211         fields.put("seed", seed.get());
1212         fields.put("nextNextGaussian", nextNextGaussian);
1213         fields.put("haveNextNextGaussian", haveNextNextGaussian);
1214 
1215         // save them
1216         s.writeFields();
1217     }
1218 
1219     // Support for resetting seed while deserializing
1220     private static final Unsafe unsafe = Unsafe.getUnsafe();
1221     private static final long seedOffset;
1222     static {
1223         try {
1224             seedOffset = unsafe.objectFieldOffset
1225                 (Random.class.getDeclaredField("seed"));
1226         } catch (Exception ex) { throw new Error(ex); }
1227     }
resetSeed(long seedVal)1228     private void resetSeed(long seedVal) {
1229         unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
1230     }
1231 }
1232