View Javadoc
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      */
104     public Random() {
105         this(seedUniquifier() ^ System.nanoTime());
106     }
107 
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      */
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 
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      */
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      */
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      */
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      */
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      */
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      */
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<sup>32</sup> possible
316      * {@code int} values are produced with (approximately) equal probability.
317      *
318      * <p>The method {@code nextInt} is implemented by class {@code Random}
319      * as if by:
320      *  <pre> {@code
321      * public int nextInt() {
322      *   return next(32);
323      * }}</pre>
324      *
325      * @return the next pseudorandom, uniformly distributed {@code int}
326      *         value from this random number generator's sequence
327      */
328     public int nextInt() {
329         return next(32);
330     }
331 
332     /**
333      * Returns a pseudorandom, uniformly distributed {@code int} value
334      * between 0 (inclusive) and the specified value (exclusive), drawn from
335      * this random number generator's sequence.  The general contract of
336      * {@code nextInt} is that one {@code int} value in the specified range
337      * is pseudorandomly generated and returned.  All {@code bound} possible
338      * {@code int} values are produced with (approximately) equal
339      * probability.  The method {@code nextInt(int bound)} is implemented by
340      * class {@code Random} as if by:
341      *  <pre> {@code
342      * public int nextInt(int bound) {
343      *   if (bound <= 0)
344      *     throw new IllegalArgumentException("bound must be positive");
345      *
346      *   if ((bound & -bound) == bound)  // i.e., bound is a power of 2
347      *     return (int)((bound * (long)next(31)) >> 31);
348      *
349      *   int bits, val;
350      *   do {
351      *       bits = next(31);
352      *       val = bits % bound;
353      *   } while (bits - val + (bound-1) < 0);
354      *   return val;
355      * }}</pre>
356      *
357      * <p>The hedge "approximately" is used in the foregoing description only
358      * because the next method is only approximately an unbiased source of
359      * independently chosen bits.  If it were a perfect source of randomly
360      * chosen bits, then the algorithm shown would choose {@code int}
361      * values from the stated range with perfect uniformity.
362      * <p>
363      * The algorithm is slightly tricky.  It rejects values that would result
364      * in an uneven distribution (due to the fact that 2^31 is not divisible
365      * by n). The probability of a value being rejected depends on n.  The
366      * worst case is n=2^30+1, for which the probability of a reject is 1/2,
367      * and the expected number of iterations before the loop terminates is 2.
368      * <p>
369      * The algorithm treats the case where n is a power of two specially: it
370      * returns the correct number of high-order bits from the underlying
371      * pseudo-random number generator.  In the absence of special treatment,
372      * the correct number of <i>low-order</i> bits would be returned.  Linear
373      * congruential pseudo-random number generators such as the one
374      * implemented by this class are known to have short periods in the
375      * sequence of values of their low-order bits.  Thus, this special case
376      * greatly increases the length of the sequence of values returned by
377      * successive calls to this method if n is a small power of two.
378      *
379      * @param bound the upper bound (exclusive).  Must be positive.
380      * @return the next pseudorandom, uniformly distributed {@code int}
381      *         value between zero (inclusive) and {@code bound} (exclusive)
382      *         from this random number generator's sequence
383      * @throws IllegalArgumentException if bound is not positive
384      * @since 1.2
385      */
386     public int nextInt(int bound) {
387         if (bound <= 0)
388             throw new IllegalArgumentException(BadBound);
389 
390         int r = next(31);
391         int m = bound - 1;
392         if ((bound & m) == 0)  // i.e., bound is a power of 2
393             r = (int)((bound * (long)r) >> 31);
394         else {
395             for (int u = r;
396                  u - (r = u % bound) + m < 0;
397                  u = next(31))
398                 ;
399         }
400         return r;
401     }
402 
403     /**
404      * Returns the next pseudorandom, uniformly distributed {@code long}
405      * value from this random number generator's sequence. The general
406      * contract of {@code nextLong} is that one {@code long} value is
407      * pseudorandomly generated and returned.
408      *
409      * <p>The method {@code nextLong} is implemented by class {@code Random}
410      * as if by:
411      *  <pre> {@code
412      * public long nextLong() {
413      *   return ((long)next(32) << 32) + next(32);
414      * }}</pre>
415      *
416      * Because class {@code Random} uses a seed with only 48 bits,
417      * this algorithm will not return all possible {@code long} values.
418      *
419      * @return the next pseudorandom, uniformly distributed {@code long}
420      *         value from this random number generator's sequence
421      */
422     public long nextLong() {
423         // it's okay that the bottom word remains signed.
424         return ((long)(next(32)) << 32) + next(32);
425     }
426 
427     /**
428      * Returns the next pseudorandom, uniformly distributed
429      * {@code boolean} value from this random number generator's
430      * sequence. The general contract of {@code nextBoolean} is that one
431      * {@code boolean} value is pseudorandomly generated and returned.  The
432      * values {@code true} and {@code false} are produced with
433      * (approximately) equal probability.
434      *
435      * <p>The method {@code nextBoolean} is implemented by class {@code Random}
436      * as if by:
437      *  <pre> {@code
438      * public boolean nextBoolean() {
439      *   return next(1) != 0;
440      * }}</pre>
441      *
442      * @return the next pseudorandom, uniformly distributed
443      *         {@code boolean} value from this random number generator's
444      *         sequence
445      * @since 1.2
446      */
447     public boolean nextBoolean() {
448         return next(1) != 0;
449     }
450 
451     /**
452      * Returns the next pseudorandom, uniformly distributed {@code float}
453      * value between {@code 0.0} and {@code 1.0} from this random
454      * number generator's sequence.
455      *
456      * <p>The general contract of {@code nextFloat} is that one
457      * {@code float} value, chosen (approximately) uniformly from the
458      * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
459      * pseudorandomly generated and returned. All 2<sup>24</sup> possible
460      * {@code float} values of the form <i>m&nbsp;x&nbsp;</i>2<sup>-24</sup>,
461      * where <i>m</i> is a positive integer less than 2<sup>24</sup>, are
462      * produced with (approximately) equal probability.
463      *
464      * <p>The method {@code nextFloat} is implemented by class {@code Random}
465      * as if by:
466      *  <pre> {@code
467      * public float nextFloat() {
468      *   return next(24) / ((float)(1 << 24));
469      * }}</pre>
470      *
471      * <p>The hedge "approximately" is used in the foregoing description only
472      * because the next method is only approximately an unbiased source of
473      * independently chosen bits. If it were a perfect source of randomly
474      * chosen bits, then the algorithm shown would choose {@code float}
475      * values from the stated range with perfect uniformity.<p>
476      * [In early versions of Java, the result was incorrectly calculated as:
477      *  <pre> {@code
478      *   return next(30) / ((float)(1 << 30));}</pre>
479      * This might seem to be equivalent, if not better, but in fact it
480      * introduced a slight nonuniformity because of the bias in the rounding
481      * of floating-point numbers: it was slightly more likely that the
482      * low-order bit of the significand would be 0 than that it would be 1.]
483      *
484      * @return the next pseudorandom, uniformly distributed {@code float}
485      *         value between {@code 0.0} and {@code 1.0} from this
486      *         random number generator's sequence
487      */
488     public float nextFloat() {
489         return next(24) / ((float)(1 << 24));
490     }
491 
492     /**
493      * Returns the next pseudorandom, uniformly distributed
494      * {@code double} value between {@code 0.0} and
495      * {@code 1.0} from this random number generator's sequence.
496      *
497      * <p>The general contract of {@code nextDouble} is that one
498      * {@code double} value, chosen (approximately) uniformly from the
499      * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
500      * pseudorandomly generated and returned.
501      *
502      * <p>The method {@code nextDouble} is implemented by class {@code Random}
503      * as if by:
504      *  <pre> {@code
505      * public double nextDouble() {
506      *   return (((long)next(26) << 27) + next(27))
507      *     / (double)(1L << 53);
508      * }}</pre>
509      *
510      * <p>The hedge "approximately" is used in the foregoing description only
511      * because the {@code next} method is only approximately an unbiased
512      * source of independently chosen bits. If it were a perfect source of
513      * randomly chosen bits, then the algorithm shown would choose
514      * {@code double} values from the stated range with perfect uniformity.
515      * <p>[In early versions of Java, the result was incorrectly calculated as:
516      *  <pre> {@code
517      *   return (((long)next(27) << 27) + next(27))
518      *     / (double)(1L << 54);}</pre>
519      * This might seem to be equivalent, if not better, but in fact it
520      * introduced a large nonuniformity because of the bias in the rounding
521      * of floating-point numbers: it was three times as likely that the
522      * low-order bit of the significand would be 0 than that it would be 1!
523      * This nonuniformity probably doesn't matter much in practice, but we
524      * strive for perfection.]
525      *
526      * @return the next pseudorandom, uniformly distributed {@code double}
527      *         value between {@code 0.0} and {@code 1.0} from this
528      *         random number generator's sequence
529      * @see Math#random
530      */
531     public double nextDouble() {
532         return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
533     }
534 
535     private double nextNextGaussian;
536     private boolean haveNextNextGaussian = false;
537 
538     /**
539      * Returns the next pseudorandom, Gaussian ("normally") distributed
540      * {@code double} value with mean {@code 0.0} and standard
541      * deviation {@code 1.0} from this random number generator's sequence.
542      * <p>
543      * The general contract of {@code nextGaussian} is that one
544      * {@code double} value, chosen from (approximately) the usual
545      * normal distribution with mean {@code 0.0} and standard deviation
546      * {@code 1.0}, is pseudorandomly generated and returned.
547      *
548      * <p>The method {@code nextGaussian} is implemented by class
549      * {@code Random} as if by a threadsafe version of the following:
550      *  <pre> {@code
551      * private double nextNextGaussian;
552      * private boolean haveNextNextGaussian = false;
553      *
554      * public double nextGaussian() {
555      *   if (haveNextNextGaussian) {
556      *     haveNextNextGaussian = false;
557      *     return nextNextGaussian;
558      *   } else {
559      *     double v1, v2, s;
560      *     do {
561      *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
562      *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
563      *       s = v1 * v1 + v2 * v2;
564      *     } while (s >= 1 || s == 0);
565      *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
566      *     nextNextGaussian = v2 * multiplier;
567      *     haveNextNextGaussian = true;
568      *     return v1 * multiplier;
569      *   }
570      * }}</pre>
571      * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
572      * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
573      * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
574      * section 3.4.1, subsection C, algorithm P. Note that it generates two
575      * independent values at the cost of only one call to {@code StrictMath.log}
576      * and one call to {@code StrictMath.sqrt}.
577      *
578      * @return the next pseudorandom, Gaussian ("normally") distributed
579      *         {@code double} value with mean {@code 0.0} and
580      *         standard deviation {@code 1.0} from this random number
581      *         generator's sequence
582      */
583     synchronized public double nextGaussian() {
584         // See Knuth, ACP, Section 3.4.1 Algorithm C.
585         if (haveNextNextGaussian) {
586             haveNextNextGaussian = false;
587             return nextNextGaussian;
588         } else {
589             double v1, v2, s;
590             do {
591                 v1 = 2 * nextDouble() - 1; // between -1 and 1
592                 v2 = 2 * nextDouble() - 1; // between -1 and 1
593                 s = v1 * v1 + v2 * v2;
594             } while (s >= 1 || s == 0);
595             double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
596             nextNextGaussian = v2 * multiplier;
597             haveNextNextGaussian = true;
598             return v1 * multiplier;
599         }
600     }
601 
602     // stream methods, coded in a way intended to better isolate for
603     // maintenance purposes the small differences across forms.
604 
605     /**
606      * Returns a stream producing the given {@code streamSize} number of
607      * pseudorandom {@code int} values.
608      *
609      * <p>A pseudorandom {@code int} value is generated as if it's the result of
610      * calling the method {@link #nextInt()}.
611      *
612      * @param streamSize the number of values to generate
613      * @return a stream of pseudorandom {@code int} values
614      * @throws IllegalArgumentException if {@code streamSize} is
615      *         less than zero
616      * @since 1.8
617      */
618     public IntStream ints(long streamSize) {
619         if (streamSize < 0L)
620             throw new IllegalArgumentException(BadSize);
621         return StreamSupport.intStream
622                 (new RandomIntsSpliterator
623                          (this, 0L, streamSize, Integer.MAX_VALUE, 0),
624                  false);
625     }
626 
627     /**
628      * Returns an effectively unlimited stream of pseudorandom {@code int}
629      * values.
630      *
631      * <p>A pseudorandom {@code int} value is generated as if it's the result of
632      * calling the method {@link #nextInt()}.
633      *
634      * @implNote This method is implemented to be equivalent to {@code
635      * ints(Long.MAX_VALUE)}.
636      *
637      * @return a stream of pseudorandom {@code int} values
638      * @since 1.8
639      */
640     public IntStream ints() {
641         return StreamSupport.intStream
642                 (new RandomIntsSpliterator
643                          (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
644                  false);
645     }
646 
647     /**
648      * Returns a stream producing the given {@code streamSize} number
649      * of pseudorandom {@code int} values, each conforming to the given
650      * origin (inclusive) and bound (exclusive).
651      *
652      * <p>A pseudorandom {@code int} value is generated as if it's the result of
653      * calling the following method with the origin and bound:
654      * <pre> {@code
655      * int nextInt(int origin, int bound) {
656      *   int n = bound - origin;
657      *   if (n > 0) {
658      *     return nextInt(n) + origin;
659      *   }
660      *   else {  // range not representable as int
661      *     int r;
662      *     do {
663      *       r = nextInt();
664      *     } while (r < origin || r >= bound);
665      *     return r;
666      *   }
667      * }}</pre>
668      *
669      * @param streamSize the number of values to generate
670      * @param randomNumberOrigin the origin (inclusive) of each random value
671      * @param randomNumberBound the bound (exclusive) of each random value
672      * @return a stream of pseudorandom {@code int} values,
673      *         each with the given origin (inclusive) and bound (exclusive)
674      * @throws IllegalArgumentException if {@code streamSize} is
675      *         less than zero, or {@code randomNumberOrigin}
676      *         is greater than or equal to {@code randomNumberBound}
677      * @since 1.8
678      */
679     public IntStream ints(long streamSize, int randomNumberOrigin,
680                           int randomNumberBound) {
681         if (streamSize < 0L)
682             throw new IllegalArgumentException(BadSize);
683         if (randomNumberOrigin >= randomNumberBound)
684             throw new IllegalArgumentException(BadRange);
685         return StreamSupport.intStream
686                 (new RandomIntsSpliterator
687                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
688                  false);
689     }
690 
691     /**
692      * Returns an effectively unlimited stream of pseudorandom {@code
693      * int} values, each conforming to the given origin (inclusive) and bound
694      * (exclusive).
695      *
696      * <p>A pseudorandom {@code int} value is generated as if it's the result of
697      * calling the following method with the origin and bound:
698      * <pre> {@code
699      * int nextInt(int origin, int bound) {
700      *   int n = bound - origin;
701      *   if (n > 0) {
702      *     return nextInt(n) + origin;
703      *   }
704      *   else {  // range not representable as int
705      *     int r;
706      *     do {
707      *       r = nextInt();
708      *     } while (r < origin || r >= bound);
709      *     return r;
710      *   }
711      * }}</pre>
712      *
713      * @implNote This method is implemented to be equivalent to {@code
714      * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
715      *
716      * @param randomNumberOrigin the origin (inclusive) of each random value
717      * @param randomNumberBound the bound (exclusive) of each random value
718      * @return a stream of pseudorandom {@code int} values,
719      *         each with the given origin (inclusive) and bound (exclusive)
720      * @throws IllegalArgumentException if {@code randomNumberOrigin}
721      *         is greater than or equal to {@code randomNumberBound}
722      * @since 1.8
723      */
724     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
725         if (randomNumberOrigin >= randomNumberBound)
726             throw new IllegalArgumentException(BadRange);
727         return StreamSupport.intStream
728                 (new RandomIntsSpliterator
729                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
730                  false);
731     }
732 
733     /**
734      * Returns a stream producing the given {@code streamSize} number of
735      * pseudorandom {@code long} values.
736      *
737      * <p>A pseudorandom {@code long} value is generated as if it's the result
738      * of calling the method {@link #nextLong()}.
739      *
740      * @param streamSize the number of values to generate
741      * @return a stream of pseudorandom {@code long} values
742      * @throws IllegalArgumentException if {@code streamSize} is
743      *         less than zero
744      * @since 1.8
745      */
746     public LongStream longs(long streamSize) {
747         if (streamSize < 0L)
748             throw new IllegalArgumentException(BadSize);
749         return StreamSupport.longStream
750                 (new RandomLongsSpliterator
751                          (this, 0L, streamSize, Long.MAX_VALUE, 0L),
752                  false);
753     }
754 
755     /**
756      * Returns an effectively unlimited stream of pseudorandom {@code long}
757      * values.
758      *
759      * <p>A pseudorandom {@code long} value is generated as if it's the result
760      * of calling the method {@link #nextLong()}.
761      *
762      * @implNote This method is implemented to be equivalent to {@code
763      * longs(Long.MAX_VALUE)}.
764      *
765      * @return a stream of pseudorandom {@code long} values
766      * @since 1.8
767      */
768     public LongStream longs() {
769         return StreamSupport.longStream
770                 (new RandomLongsSpliterator
771                          (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
772                  false);
773     }
774 
775     /**
776      * Returns a stream producing the given {@code streamSize} number of
777      * pseudorandom {@code long}, each conforming to the given origin
778      * (inclusive) and bound (exclusive).
779      *
780      * <p>A pseudorandom {@code long} value is generated as if it's the result
781      * of calling the following method with the origin and bound:
782      * <pre> {@code
783      * long nextLong(long origin, long bound) {
784      *   long r = nextLong();
785      *   long n = bound - origin, m = n - 1;
786      *   if ((n & m) == 0L)  // power of two
787      *     r = (r & m) + origin;
788      *   else if (n > 0L) {  // reject over-represented candidates
789      *     for (long u = r >>> 1;            // ensure nonnegative
790      *          u + m - (r = u % n) < 0L;    // rejection check
791      *          u = nextLong() >>> 1) // retry
792      *         ;
793      *     r += origin;
794      *   }
795      *   else {              // range not representable as long
796      *     while (r < origin || r >= bound)
797      *       r = nextLong();
798      *   }
799      *   return r;
800      * }}</pre>
801      *
802      * @param streamSize the number of values to generate
803      * @param randomNumberOrigin the origin (inclusive) of each random value
804      * @param randomNumberBound the bound (exclusive) of each random value
805      * @return a stream of pseudorandom {@code long} values,
806      *         each with the given origin (inclusive) and bound (exclusive)
807      * @throws IllegalArgumentException if {@code streamSize} is
808      *         less than zero, or {@code randomNumberOrigin}
809      *         is greater than or equal to {@code randomNumberBound}
810      * @since 1.8
811      */
812     public LongStream longs(long streamSize, long randomNumberOrigin,
813                             long randomNumberBound) {
814         if (streamSize < 0L)
815             throw new IllegalArgumentException(BadSize);
816         if (randomNumberOrigin >= randomNumberBound)
817             throw new IllegalArgumentException(BadRange);
818         return StreamSupport.longStream
819                 (new RandomLongsSpliterator
820                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
821                  false);
822     }
823 
824     /**
825      * Returns an effectively unlimited stream of pseudorandom {@code
826      * long} values, each conforming to the given origin (inclusive) and bound
827      * (exclusive).
828      *
829      * <p>A pseudorandom {@code long} value is generated as if it's the result
830      * of calling the following method with the origin and bound:
831      * <pre> {@code
832      * long nextLong(long origin, long bound) {
833      *   long r = nextLong();
834      *   long n = bound - origin, m = n - 1;
835      *   if ((n & m) == 0L)  // power of two
836      *     r = (r & m) + origin;
837      *   else if (n > 0L) {  // reject over-represented candidates
838      *     for (long u = r >>> 1;            // ensure nonnegative
839      *          u + m - (r = u % n) < 0L;    // rejection check
840      *          u = nextLong() >>> 1) // retry
841      *         ;
842      *     r += origin;
843      *   }
844      *   else {              // range not representable as long
845      *     while (r < origin || r >= bound)
846      *       r = nextLong();
847      *   }
848      *   return r;
849      * }}</pre>
850      *
851      * @implNote This method is implemented to be equivalent to {@code
852      * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
853      *
854      * @param randomNumberOrigin the origin (inclusive) of each random value
855      * @param randomNumberBound the bound (exclusive) of each random value
856      * @return a stream of pseudorandom {@code long} values,
857      *         each with the given origin (inclusive) and bound (exclusive)
858      * @throws IllegalArgumentException if {@code randomNumberOrigin}
859      *         is greater than or equal to {@code randomNumberBound}
860      * @since 1.8
861      */
862     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
863         if (randomNumberOrigin >= randomNumberBound)
864             throw new IllegalArgumentException(BadRange);
865         return StreamSupport.longStream
866                 (new RandomLongsSpliterator
867                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
868                  false);
869     }
870 
871     /**
872      * Returns a stream producing the given {@code streamSize} number of
873      * pseudorandom {@code double} values, each between zero
874      * (inclusive) and one (exclusive).
875      *
876      * <p>A pseudorandom {@code double} value is generated as if it's the result
877      * of calling the method {@link #nextDouble()}}.
878      *
879      * @param streamSize the number of values to generate
880      * @return a stream of {@code double} values
881      * @throws IllegalArgumentException if {@code streamSize} is
882      *         less than zero
883      * @since 1.8
884      */
885     public DoubleStream doubles(long streamSize) {
886         if (streamSize < 0L)
887             throw new IllegalArgumentException(BadSize);
888         return StreamSupport.doubleStream
889                 (new RandomDoublesSpliterator
890                          (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
891                  false);
892     }
893 
894     /**
895      * Returns an effectively unlimited stream of pseudorandom {@code
896      * double} values, each between zero (inclusive) and one
897      * (exclusive).
898      *
899      * <p>A pseudorandom {@code double} value is generated as if it's the result
900      * of calling the method {@link #nextDouble()}}.
901      *
902      * @implNote This method is implemented to be equivalent to {@code
903      * doubles(Long.MAX_VALUE)}.
904      *
905      * @return a stream of pseudorandom {@code double} values
906      * @since 1.8
907      */
908     public DoubleStream doubles() {
909         return StreamSupport.doubleStream
910                 (new RandomDoublesSpliterator
911                          (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
912                  false);
913     }
914 
915     /**
916      * Returns a stream producing the given {@code streamSize} number of
917      * pseudorandom {@code double} values, each conforming to the given origin
918      * (inclusive) and bound (exclusive).
919      *
920      * <p>A pseudorandom {@code double} value is generated as if it's the result
921      * of calling the following method with the origin and bound:
922      * <pre> {@code
923      * double nextDouble(double origin, double bound) {
924      *   double r = nextDouble();
925      *   r = r * (bound - origin) + origin;
926      *   if (r >= bound) // correct for rounding
927      *     r = Math.nextDown(bound);
928      *   return r;
929      * }}</pre>
930      *
931      * @param streamSize the number of values to generate
932      * @param randomNumberOrigin the origin (inclusive) of each random value
933      * @param randomNumberBound the bound (exclusive) of each random value
934      * @return a stream of pseudorandom {@code double} values,
935      *         each with the given origin (inclusive) and bound (exclusive)
936      * @throws IllegalArgumentException if {@code streamSize} is
937      *         less than zero
938      * @throws IllegalArgumentException if {@code randomNumberOrigin}
939      *         is greater than or equal to {@code randomNumberBound}
940      * @since 1.8
941      */
942     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
943                                 double randomNumberBound) {
944         if (streamSize < 0L)
945             throw new IllegalArgumentException(BadSize);
946         if (!(randomNumberOrigin < randomNumberBound))
947             throw new IllegalArgumentException(BadRange);
948         return StreamSupport.doubleStream
949                 (new RandomDoublesSpliterator
950                          (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
951                  false);
952     }
953 
954     /**
955      * Returns an effectively unlimited stream of pseudorandom {@code
956      * double} values, each conforming to the given origin (inclusive) and bound
957      * (exclusive).
958      *
959      * <p>A pseudorandom {@code double} value is generated as if it's the result
960      * of calling the following method with the origin and bound:
961      * <pre> {@code
962      * double nextDouble(double origin, double bound) {
963      *   double r = nextDouble();
964      *   r = r * (bound - origin) + origin;
965      *   if (r >= bound) // correct for rounding
966      *     r = Math.nextDown(bound);
967      *   return r;
968      * }}</pre>
969      *
970      * @implNote This method is implemented to be equivalent to {@code
971      * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
972      *
973      * @param randomNumberOrigin the origin (inclusive) of each random value
974      * @param randomNumberBound the bound (exclusive) of each random value
975      * @return a stream of pseudorandom {@code double} values,
976      *         each with the given origin (inclusive) and bound (exclusive)
977      * @throws IllegalArgumentException if {@code randomNumberOrigin}
978      *         is greater than or equal to {@code randomNumberBound}
979      * @since 1.8
980      */
981     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
982         if (!(randomNumberOrigin < randomNumberBound))
983             throw new IllegalArgumentException(BadRange);
984         return StreamSupport.doubleStream
985                 (new RandomDoublesSpliterator
986                          (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
987                  false);
988     }
989 
990     /**
991      * Spliterator for int streams.  We multiplex the four int
992      * versions into one class by treating a bound less than origin as
993      * unbounded, and also by treating "infinite" as equivalent to
994      * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
995      * approach. The long and double versions of this class are
996      * identical except for types.
997      */
998     static final class RandomIntsSpliterator implements Spliterator.OfInt {
999         final Random rng;
1000         long index;
1001         final long fence;
1002         final int origin;
1003         final int bound;
1004         RandomIntsSpliterator(Random rng, long index, long fence,
1005                               int origin, int bound) {
1006             this.rng = rng; this.index = index; this.fence = fence;
1007             this.origin = origin; this.bound = bound;
1008         }
1009 
1010         public RandomIntsSpliterator trySplit() {
1011             long i = index, m = (i + fence) >>> 1;
1012             return (m <= i) ? null :
1013                    new RandomIntsSpliterator(rng, i, index = m, origin, bound);
1014         }
1015 
1016         public long estimateSize() {
1017             return fence - index;
1018         }
1019 
1020         public int characteristics() {
1021             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1022                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1023         }
1024 
1025         public boolean tryAdvance(IntConsumer consumer) {
1026             if (consumer == null) throw new NullPointerException();
1027             long i = index, f = fence;
1028             if (i < f) {
1029                 consumer.accept(rng.internalNextInt(origin, bound));
1030                 index = i + 1;
1031                 return true;
1032             }
1033             return false;
1034         }
1035 
1036         public void forEachRemaining(IntConsumer consumer) {
1037             if (consumer == null) throw new NullPointerException();
1038             long i = index, f = fence;
1039             if (i < f) {
1040                 index = f;
1041                 Random r = rng;
1042                 int o = origin, b = bound;
1043                 do {
1044                     consumer.accept(r.internalNextInt(o, b));
1045                 } while (++i < f);
1046             }
1047         }
1048     }
1049 
1050     /**
1051      * Spliterator for long streams.
1052      */
1053     static final class RandomLongsSpliterator implements Spliterator.OfLong {
1054         final Random rng;
1055         long index;
1056         final long fence;
1057         final long origin;
1058         final long bound;
1059         RandomLongsSpliterator(Random rng, long index, long fence,
1060                                long origin, long bound) {
1061             this.rng = rng; this.index = index; this.fence = fence;
1062             this.origin = origin; this.bound = bound;
1063         }
1064 
1065         public RandomLongsSpliterator trySplit() {
1066             long i = index, m = (i + fence) >>> 1;
1067             return (m <= i) ? null :
1068                    new RandomLongsSpliterator(rng, i, index = m, origin, bound);
1069         }
1070 
1071         public long estimateSize() {
1072             return fence - index;
1073         }
1074 
1075         public int characteristics() {
1076             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1077                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1078         }
1079 
1080         public boolean tryAdvance(LongConsumer consumer) {
1081             if (consumer == null) throw new NullPointerException();
1082             long i = index, f = fence;
1083             if (i < f) {
1084                 consumer.accept(rng.internalNextLong(origin, bound));
1085                 index = i + 1;
1086                 return true;
1087             }
1088             return false;
1089         }
1090 
1091         public void forEachRemaining(LongConsumer consumer) {
1092             if (consumer == null) throw new NullPointerException();
1093             long i = index, f = fence;
1094             if (i < f) {
1095                 index = f;
1096                 Random r = rng;
1097                 long o = origin, b = bound;
1098                 do {
1099                     consumer.accept(r.internalNextLong(o, b));
1100                 } while (++i < f);
1101             }
1102         }
1103 
1104     }
1105 
1106     /**
1107      * Spliterator for double streams.
1108      */
1109     static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
1110         final Random rng;
1111         long index;
1112         final long fence;
1113         final double origin;
1114         final double bound;
1115         RandomDoublesSpliterator(Random rng, long index, long fence,
1116                                  double origin, double bound) {
1117             this.rng = rng; this.index = index; this.fence = fence;
1118             this.origin = origin; this.bound = bound;
1119         }
1120 
1121         public RandomDoublesSpliterator trySplit() {
1122             long i = index, m = (i + fence) >>> 1;
1123             return (m <= i) ? null :
1124                    new RandomDoublesSpliterator(rng, i, index = m, origin, bound);
1125         }
1126 
1127         public long estimateSize() {
1128             return fence - index;
1129         }
1130 
1131         public int characteristics() {
1132             return (Spliterator.SIZED | Spliterator.SUBSIZED |
1133                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
1134         }
1135 
1136         public boolean tryAdvance(DoubleConsumer consumer) {
1137             if (consumer == null) throw new NullPointerException();
1138             long i = index, f = fence;
1139             if (i < f) {
1140                 consumer.accept(rng.internalNextDouble(origin, bound));
1141                 index = i + 1;
1142                 return true;
1143             }
1144             return false;
1145         }
1146 
1147         public void forEachRemaining(DoubleConsumer consumer) {
1148             if (consumer == null) throw new NullPointerException();
1149             long i = index, f = fence;
1150             if (i < f) {
1151                 index = f;
1152                 Random r = rng;
1153                 double o = origin, b = bound;
1154                 do {
1155                     consumer.accept(r.internalNextDouble(o, b));
1156                 } while (++i < f);
1157             }
1158         }
1159     }
1160 
1161     /**
1162      * Serializable fields for Random.
1163      *
1164      * @serialField    seed long
1165      *              seed for random computations
1166      * @serialField    nextNextGaussian double
1167      *              next Gaussian to be returned
1168      * @serialField      haveNextNextGaussian boolean
1169      *              nextNextGaussian is valid
1170      */
1171     private static final ObjectStreamField[] serialPersistentFields = {
1172         new ObjectStreamField("seed", Long.TYPE),
1173         new ObjectStreamField("nextNextGaussian", Double.TYPE),
1174         new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
1175     };
1176 
1177     /**
1178      * Reconstitute the {@code Random} instance from a stream (that is,
1179      * deserialize it).
1180      */
1181     private void readObject(java.io.ObjectInputStream s)
1182         throws java.io.IOException, ClassNotFoundException {
1183 
1184         ObjectInputStream.GetField fields = s.readFields();
1185 
1186         // The seed is read in as {@code long} for
1187         // historical reasons, but it is converted to an AtomicLong.
1188         long seedVal = fields.get("seed", -1L);
1189         if (seedVal < 0)
1190           throw new java.io.StreamCorruptedException(
1191                               "Random: invalid seed");
1192         resetSeed(seedVal);
1193         nextNextGaussian = fields.get("nextNextGaussian", 0.0);
1194         haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
1195     }
1196 
1197     /**
1198      * Save the {@code Random} instance to a stream.
1199      */
1200     synchronized private void writeObject(ObjectOutputStream s)
1201         throws IOException {
1202 
1203         // set the values of the Serializable fields
1204         ObjectOutputStream.PutField fields = s.putFields();
1205 
1206         // The seed is serialized as a long for historical reasons.
1207         fields.put("seed", seed.get());
1208         fields.put("nextNextGaussian", nextNextGaussian);
1209         fields.put("haveNextNextGaussian", haveNextNextGaussian);
1210 
1211         // save them
1212         s.writeFields();
1213     }
1214 
1215     // Support for resetting seed while deserializing
1216     private static final Unsafe unsafe = Unsafe.getUnsafe();
1217     private static final long seedOffset;
1218     static {
1219         try {
1220             seedOffset = unsafe.objectFieldOffset
1221                 (Random.class.getDeclaredField("seed"));
1222         } catch (Exception ex) { throw new Error(ex); }
1223     }
1224     private void resetSeed(long seedVal) {
1225         unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
1226     }
1227 }