• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1995, 2021, 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 
28 import android.compat.Compatibility;
29 import android.compat.annotation.ChangeId;
30 import android.compat.annotation.EnabledSince;
31 
32 import java.io.*;
33 import java.util.concurrent.atomic.AtomicLong;
34 import java.util.random.RandomGenerator;
35 import java.util.stream.DoubleStream;
36 import java.util.stream.IntStream;
37 import java.util.stream.LongStream;
38 
39 import jdk.internal.util.random.RandomSupport;
40 
41 import dalvik.annotation.compat.VersionCodes;
42 import dalvik.system.VMRuntime;
43 
44 import static jdk.internal.util.random.RandomSupport.*;
45 
46 import jdk.internal.misc.Unsafe;
47 
48 /**
49  * An instance of this class is used to generate a stream of
50  * pseudorandom numbers; its period is only 2<sup>48</sup>.
51  * The class uses a 48-bit seed, which is
52  * modified using a linear congruential formula. (See Donald E. Knuth,
53  * <cite>The Art of Computer Programming, Volume 2, Third
54  * edition: Seminumerical Algorithms</cite>, Section 3.2.1.)
55  * <p>
56  * If two instances of {@code Random} are created with the same
57  * seed, and the same sequence of method calls is made for each, they
58  * will generate and return identical sequences of numbers. In order to
59  * guarantee this property, particular algorithms are specified for the
60  * class {@code Random}. Java implementations must use all the algorithms
61  * shown here for the class {@code Random}, for the sake of absolute
62  * portability of Java code. However, subclasses of class {@code Random}
63  * are permitted to use other algorithms, so long as they adhere to the
64  * general contracts for all the methods.
65  * <p>
66  * The algorithms implemented by class {@code Random} use a
67  * {@code protected} utility method that on each invocation can supply
68  * up to 32 pseudorandomly generated bits.
69  * <p>
70  * Many applications will find the method {@link Math#random} simpler to use.
71  *
72  * <p>Instances of {@code java.util.Random} are threadsafe.
73  * However, the concurrent use of the same {@code java.util.Random}
74  * instance across threads may encounter contention and consequent
75  * poor performance. Consider instead using
76  * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
77  * designs.
78  *
79  * <p>Instances of {@code java.util.Random} are not cryptographically
80  * secure.  Consider instead using {@link java.security.SecureRandom} to
81  * get a cryptographically secure pseudo-random number generator for use
82  * by security-sensitive applications.
83  *
84  * @author  Frank Yellin
85  * @since   1.0
86  */
87 @SuppressWarnings("exports")
88 @RandomGeneratorProperties(
89         name = "Random",
90         i = 48, j = 0, k = 0,
91         equidistribution = 0
92 )
93 public class Random implements RandomGenerator, java.io.Serializable {
94     /** use serialVersionUID from JDK 1.1 for interoperability */
95     @java.io.Serial
96     static final long serialVersionUID = 3905348978240129619L;
97 
98     /**
99      * The internal state associated with this pseudorandom number generator.
100      * (The specs for the methods in this class describe the ongoing
101      * computation of this value.)
102      */
103     private final AtomicLong seed;
104 
105     private static final long multiplier = 0x5DEECE66DL;
106     private static final long addend = 0xBL;
107     private static final long mask = (1L << 48) - 1;
108 
109     private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
110 
111     // Android-added: flag to keep old behaviour of Random.ints().
112     /**
113      * After https://bugs.openjdk.org/browse/JDK-8301574 ints()
114      * and long() methods generate different sequence of number
115      * than nextInt() and nextLong() calls would.
116      *
117      * @hide
118      */
119     @ChangeId
120     @EnabledSince(targetSdkVersion = VersionCodes.VANILLA_ICE_CREAM)
121     public static final long STREAM_INT_DIFFERS_FROM_NEXT_INT = 308103782L;
122 
123     /**
124      * Creates a new random number generator. This constructor sets
125      * the seed of the random number generator to a value very likely
126      * to be distinct from any other invocation of this constructor.
127      */
Random()128     public Random() {
129         this(seedUniquifier() ^ System.nanoTime());
130     }
131 
seedUniquifier()132     private static long seedUniquifier() {
133         // L'Ecuyer, "Tables of Linear Congruential Generators of
134         // Different Sizes and Good Lattice Structure", 1999
135         for (;;) {
136             long current = seedUniquifier.get();
137             long next = current * 1181783497276652981L;
138             if (seedUniquifier.compareAndSet(current, next))
139                 return next;
140         }
141     }
142 
143     private static final AtomicLong seedUniquifier
144             = new AtomicLong(8682522807148012L);
145 
146     /**
147      * Creates a new random number generator using a single {@code long} seed.
148      * The seed is the initial value of the internal state of the pseudorandom
149      * number generator which is maintained by method {@link #next}.
150      *
151      * @implSpec The invocation {@code new Random(seed)} is equivalent to:
152      * <pre>{@code
153      * Random rnd = new Random();
154      * rnd.setSeed(seed);
155      * }</pre>
156      *
157      * @param seed the initial seed
158      * @see   #setSeed(long)
159      */
Random(long seed)160     public Random(long seed) {
161         if (getClass() == Random.class)
162             this.seed = new AtomicLong(initialScramble(seed));
163         else {
164             // subclass might have overridden setSeed
165             this.seed = new AtomicLong();
166             setSeed(seed);
167         }
168     }
169 
initialScramble(long seed)170     private static long initialScramble(long seed) {
171         return (seed ^ multiplier) & mask;
172     }
173 
174     /**
175      * Sets the seed of this random number generator using a single
176      * {@code long} seed. The general contract of {@code setSeed} is
177      * that it alters the state of this random number generator object
178      * so as to be in exactly the same state as if it had just been
179      * created with the argument {@code seed} as a seed. The method
180      * {@code setSeed} is implemented by class {@code Random} by
181      * atomically updating the seed to
182      *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
183      * and clearing the {@code haveNextNextGaussian} flag used by {@link
184      * #nextGaussian}.
185      *
186      * <p>The implementation of {@code setSeed} by class {@code Random}
187      * happens to use only 48 bits of the given seed. In general, however,
188      * an overriding method may use all 64 bits of the {@code long}
189      * argument as a seed value.
190      *
191      * @param seed the initial seed
192      */
setSeed(long seed)193     public synchronized void setSeed(long seed) {
194         this.seed.set(initialScramble(seed));
195         haveNextNextGaussian = false;
196     }
197 
198     /**
199      * Generates the next pseudorandom number. Subclasses should
200      * override this, as this is used by all other methods.
201      *
202      * <p>The general contract of {@code next} is that it returns an
203      * {@code int} value and if the argument {@code bits} is between
204      * {@code 1} and {@code 32} (inclusive), then that many low-order
205      * bits of the returned value will be (approximately) independently
206      * chosen bit values, each of which is (approximately) equally
207      * likely to be {@code 0} or {@code 1}. The method {@code next} is
208      * implemented by class {@code Random} by atomically updating the seed to
209      *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
210      * and returning
211      *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
212      *
213      * This is a linear congruential pseudorandom number generator, as
214      * defined by D. H. Lehmer and described by Donald E. Knuth in
215      * <cite>The Art of Computer Programming, Volume 2, Third edition:
216      * Seminumerical Algorithms</cite>, section 3.2.1.
217      *
218      * @param  bits random bits
219      * @return the next pseudorandom value from this random number
220      *         generator's sequence
221      * @since  1.1
222      */
next(int bits)223     protected int next(int bits) {
224         long oldseed, nextseed;
225         AtomicLong seed = this.seed;
226         do {
227             oldseed = seed.get();
228             nextseed = (oldseed * multiplier + addend) & mask;
229         } while (!seed.compareAndSet(oldseed, nextseed));
230         return (int)(nextseed >>> (48 - bits));
231     }
232 
233     /**
234      * Generates random bytes and places them into a user-supplied
235      * byte array.  The number of random bytes produced is equal to
236      * the length of the byte array.
237      *
238      * @implSpec The method {@code nextBytes} is
239      * implemented by class {@code Random} as if by:
240      * <pre>{@code
241      * public void nextBytes(byte[] bytes) {
242      *   for (int i = 0; i < bytes.length; )
243      *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
244      *          n-- > 0; rnd >>= 8)
245      *       bytes[i++] = (byte)rnd;
246      * }}</pre>
247      *
248      * @param  bytes the byte array to fill with random bytes
249      * @throws NullPointerException if the byte array is null
250      * @since  1.1
251      */
252     @Override
nextBytes(byte[] bytes)253     public void nextBytes(byte[] bytes) {
254         for (int i = 0, len = bytes.length; i < len; )
255             for (int rnd = nextInt(),
256                  n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
257                  n-- > 0; rnd >>= Byte.SIZE)
258                 bytes[i++] = (byte)rnd;
259     }
260 
261     /**
262      * Returns the next pseudorandom, uniformly distributed {@code int}
263      * value from this random number generator's sequence. The general
264      * contract of {@code nextInt} is that one {@code int} value is
265      * pseudorandomly generated and returned. All 2<sup>32</sup> possible
266      * {@code int} values are produced with (approximately) equal probability.
267      *
268      * @implSpec The method {@code nextInt} is
269      * implemented by class {@code Random} as if by:
270      * <pre>{@code
271      * public int nextInt() {
272      *   return next(32);
273      * }}</pre>
274      *
275      * @return the next pseudorandom, uniformly distributed {@code int}
276      *         value from this random number generator's sequence
277      */
278     @Override
nextInt()279     public int nextInt() {
280         return next(32);
281     }
282 
283     /**
284      * Returns a pseudorandom, uniformly distributed {@code int} value
285      * between 0 (inclusive) and the specified value (exclusive), drawn from
286      * this random number generator's sequence.  The general contract of
287      * {@code nextInt} is that one {@code int} value in the specified range
288      * is pseudorandomly generated and returned.  All {@code bound} possible
289      * {@code int} values are produced with (approximately) equal
290      * probability.
291      *
292      * @implSpec The method {@code nextInt(int bound)} is implemented by
293      * class {@code Random} as if by:
294      * <pre>{@code
295      * public int nextInt(int bound) {
296      *   if (bound <= 0)
297      *     throw new IllegalArgumentException("bound must be positive");
298      *
299      *   if ((bound & -bound) == bound)  // i.e., bound is a power of 2
300      *     return (int)((bound * (long)next(31)) >> 31);
301      *
302      *   int bits, val;
303      *   do {
304      *       bits = next(31);
305      *       val = bits % bound;
306      *   } while (bits - val + (bound-1) < 0);
307      *   return val;
308      * }}</pre>
309      *
310      * <p>The hedge "approximately" is used in the foregoing description only
311      * because the next method is only approximately an unbiased source of
312      * independently chosen bits.  If it were a perfect source of randomly
313      * chosen bits, then the algorithm shown would choose {@code int}
314      * values from the stated range with perfect uniformity.
315      * <p>
316      * The algorithm is slightly tricky.  It rejects values that would result
317      * in an uneven distribution (due to the fact that 2^31 is not divisible
318      * by n). The probability of a value being rejected depends on n.  The
319      * worst case is n=2^30+1, for which the probability of a reject is 1/2,
320      * and the expected number of iterations before the loop terminates is 2.
321      * <p>
322      * The algorithm treats the case where n is a power of two specially: it
323      * returns the correct number of high-order bits from the underlying
324      * pseudo-random number generator.  In the absence of special treatment,
325      * the correct number of <i>low-order</i> bits would be returned.  Linear
326      * congruential pseudo-random number generators such as the one
327      * implemented by this class are known to have short periods in the
328      * sequence of values of their low-order bits.  Thus, this special case
329      * greatly increases the length of the sequence of values returned by
330      * successive calls to this method if n is a small power of two.
331      *
332      * @param bound the upper bound (exclusive).  Must be positive.
333      * @return the next pseudorandom, uniformly distributed {@code int}
334      *         value between zero (inclusive) and {@code bound} (exclusive)
335      *         from this random number generator's sequence
336      * @throws IllegalArgumentException if bound is not positive
337      * @since 1.2
338      */
339     @Override
nextInt(int bound)340     public int nextInt(int bound) {
341         if (bound <= 0)
342             throw new IllegalArgumentException(BAD_BOUND);
343         int r = next(31);
344         int m = bound - 1;
345         if ((bound & m) == 0)  // i.e., bound is a power of 2
346             r = (int)((bound * (long)r) >> 31);
347         else { // reject over-represented candidates
348             for (int u = r;
349                  u - (r = u % bound) + m < 0;
350                  u = next(31))
351                 ;
352         }
353         return r;
354     }
355     /**
356      * Returns the next pseudorandom, uniformly distributed {@code long}
357      * value from this random number generator's sequence. The general
358      * contract of {@code nextLong} is that one {@code long} value is
359      * pseudorandomly generated and returned.
360      *
361      * @implSpec The method {@code nextLong} is implemented by class {@code Random}
362      * as if by:
363      * <pre>{@code
364      * public long nextLong() {
365      *   return ((long)next(32) << 32) + next(32);
366      * }}</pre>
367      *
368      * Because class {@code Random} uses a seed with only 48 bits,
369      * this algorithm will not return all possible {@code long} values.
370      *
371      * @return the next pseudorandom, uniformly distributed {@code long}
372      *         value from this random number generator's sequence
373      */
374     @Override
nextLong()375     public long nextLong() {
376         // it's okay that the bottom word remains signed.
377         return ((long)(next(32)) << 32) + next(32);
378     }
379 
380     /**
381      * Returns the next pseudorandom, uniformly distributed
382      * {@code boolean} value from this random number generator's
383      * sequence. The general contract of {@code nextBoolean} is that one
384      * {@code boolean} value is pseudorandomly generated and returned.  The
385      * values {@code true} and {@code false} are produced with
386      * (approximately) equal probability.
387      *
388      * @implSpec The method {@code nextBoolean} is implemented by class
389      * {@code Random} as if by:
390      * <pre>{@code
391      * public boolean nextBoolean() {
392      *   return next(1) != 0;
393      * }}</pre>
394      *
395      * @return the next pseudorandom, uniformly distributed
396      *         {@code boolean} value from this random number generator's
397      *         sequence
398      * @since 1.2
399      */
400     @Override
nextBoolean()401     public boolean nextBoolean() {
402         return next(1) != 0;
403     }
404 
405     /**
406      * Returns the next pseudorandom, uniformly distributed {@code float}
407      * value between {@code 0.0} and {@code 1.0} from this random
408      * number generator's sequence.
409      *
410      * <p>The general contract of {@code nextFloat} is that one
411      * {@code float} value, chosen (approximately) uniformly from the
412      * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
413      * pseudorandomly generated and returned. All 2<sup>24</sup> possible
414      * {@code float} values of the form <i>m&nbsp;x&nbsp;</i>2<sup>-24</sup>,
415      * where <i>m</i> is a positive integer less than 2<sup>24</sup>, are
416      * produced with (approximately) equal probability.
417      *
418      * @implSpec The method {@code nextFloat} is implemented by class
419      * {@code Random} as if by:
420      * <pre>{@code
421      * public float nextFloat() {
422      *   return next(24) / ((float)(1 << 24));
423      * }}</pre>
424      * <p>The hedge "approximately" is used in the foregoing description only
425      * because the next method is only approximately an unbiased source of
426      * independently chosen bits. If it were a perfect source of randomly
427      * chosen bits, then the algorithm shown would choose {@code float}
428      * values from the stated range with perfect uniformity.<p>
429      * [In early versions of Java, the result was incorrectly calculated as:
430      *  <pre> {@code return next(30) / ((float)(1 << 30));}</pre>
431      * This might seem to be equivalent, if not better, but in fact it
432      * introduced a slight nonuniformity because of the bias in the rounding
433      * of floating-point numbers: it was slightly more likely that the
434      * low-order bit of the significand would be 0 than that it would be 1.]
435      *
436      * @return the next pseudorandom, uniformly distributed {@code float}
437      *         value between {@code 0.0} and {@code 1.0} from this
438      *         random number generator's sequence
439      */
440     @Override
nextFloat()441     public float nextFloat() {
442         return next(24) / ((float)(1 << 24));
443     }
444 
445     /**
446      * Returns the next pseudorandom, uniformly distributed
447      * {@code double} value between {@code 0.0} and
448      * {@code 1.0} from this random number generator's sequence.
449      *
450      * <p>The general contract of {@code nextDouble} is that one
451      * {@code double} value, chosen (approximately) uniformly from the
452      * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
453      * pseudorandomly generated and returned.
454      *
455      * @implSpec The method {@code nextDouble} is implemented by class
456      * {@code Random} as if by:
457      * <pre>{@code
458      * public double nextDouble() {
459      *   return (((long)next(26) << 27) + next(27))
460      *     / (double)(1L << 53);
461      * }}</pre>
462      * <p>The hedge "approximately" is used in the foregoing description only
463      * because the {@code next} method is only approximately an unbiased source
464      * of independently chosen bits. If it were a perfect source of randomly
465      * chosen bits, then the algorithm shown would choose {@code double} values
466      * from the stated range with perfect uniformity.
467      * <p>[In early versions of Java, the result was incorrectly calculated as:
468      * <pre> {@code return (((long)next(27) << 27) + next(27)) / (double)(1L << 54);}</pre>
469      * This might seem to be equivalent, if not better, but in fact it
470      * introduced a large nonuniformity because of the bias in the rounding of
471      * floating-point numbers: it was three times as likely that the low-order
472      * bit of the significand would be 0 than that it would be 1! This
473      * nonuniformity probably doesn't matter much in practice, but we strive
474      * for perfection.]
475      *
476      * @return the next pseudorandom, uniformly distributed {@code double}
477      *         value between {@code 0.0} and {@code 1.0} from this
478      *         random number generator's sequence
479      * @see Math#random
480      */
481     @Override
nextDouble()482     public double nextDouble() {
483         return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
484     }
485 
486     private double nextNextGaussian;
487     private boolean haveNextNextGaussian = false;
488 
489     /**
490      * Returns the next pseudorandom, Gaussian ("normally") distributed
491      * {@code double} value with mean {@code 0.0} and standard
492      * deviation {@code 1.0} from this random number generator's sequence.
493      * <p>
494      * The general contract of {@code nextGaussian} is that one
495      * {@code double} value, chosen from (approximately) the usual
496      * normal distribution with mean {@code 0.0} and standard deviation
497      * {@code 1.0}, is pseudorandomly generated and returned.
498      *
499      * @implSpec The method {@code nextGaussian} is implemented by class
500      * {@code Random} as if by a threadsafe version of the following:
501      * <pre>{@code
502      * private double nextNextGaussian;
503      * private boolean haveNextNextGaussian = false;
504      *
505      * public double nextGaussian() {
506      *   if (haveNextNextGaussian) {
507      *     haveNextNextGaussian = false;
508      *     return nextNextGaussian;
509      *   } else {
510      *     double v1, v2, s;
511      *     do {
512      *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
513      *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
514      *       s = v1 * v1 + v2 * v2;
515      *     } while (s >= 1 || s == 0);
516      *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
517      *     nextNextGaussian = v2 * multiplier;
518      *     haveNextNextGaussian = true;
519      *     return v1 * multiplier;
520      *   }
521      * }}</pre>
522      *
523      * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
524      * G. Marsaglia, as described by Donald E. Knuth in <cite>The Art of
525      * Computer Programming, Volume 2, third edition: Seminumerical Algorithms</cite>,
526      * section 3.4.1, subsection C, algorithm P. Note that it generates two
527      * independent values at the cost of only one call to {@code StrictMath.log}
528      * and one call to {@code StrictMath.sqrt}.
529      *
530      * @return the next pseudorandom, Gaussian ("normally") distributed
531      *         {@code double} value with mean {@code 0.0} and
532      *         standard deviation {@code 1.0} from this random number
533      *         generator's sequence
534      */
535     @Override
nextGaussian()536     public synchronized double nextGaussian() {
537         // See Knuth, TAOCP, Vol. 2, 3rd edition, Section 3.4.1 Algorithm C.
538         if (haveNextNextGaussian) {
539             haveNextNextGaussian = false;
540             return nextNextGaussian;
541         } else {
542             double v1, v2, s;
543             do {
544                 v1 = 2 * nextDouble() - 1; // between -1 and 1
545                 v2 = 2 * nextDouble() - 1; // between -1 and 1
546                 s = v1 * v1 + v2 * v2;
547             } while (s >= 1 || s == 0);
548             double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
549             nextNextGaussian = v2 * multiplier;
550             haveNextNextGaussian = true;
551             return v1 * multiplier;
552         }
553     }
554 
555     /**
556      * Serializable fields for Random.
557      *
558      * @serialField    seed long
559      *              seed for random computations
560      * @serialField    nextNextGaussian double
561      *              next Gaussian to be returned
562      * @serialField      haveNextNextGaussian boolean
563      *              nextNextGaussian is valid
564      */
565     @java.io.Serial
566     private static final ObjectStreamField[] serialPersistentFields = {
567             new ObjectStreamField("seed", Long.TYPE),
568             new ObjectStreamField("nextNextGaussian", Double.TYPE),
569             new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
570     };
571 
572     /**
573      * Reconstitute the {@code Random} instance from a stream (that is,
574      * deserialize it).
575      *
576      * @param  s the {@code ObjectInputStream} from which data is read
577      *
578      * @throws IOException if an I/O error occurs
579      * @throws ClassNotFoundException if a serialized class cannot be loaded
580      */
581     @java.io.Serial
readObject(java.io.ObjectInputStream s)582     private void readObject(java.io.ObjectInputStream s)
583             throws java.io.IOException, ClassNotFoundException {
584 
585         ObjectInputStream.GetField fields = s.readFields();
586 
587         // The seed is read in as {@code long} for
588         // historical reasons, but it is converted to an AtomicLong.
589         long seedVal = fields.get("seed", -1L);
590         if (seedVal < 0)
591             throw new java.io.StreamCorruptedException(
592                     "Random: invalid seed");
593         resetSeed(seedVal);
594         nextNextGaussian = fields.get("nextNextGaussian", 0.0);
595         haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
596     }
597 
598     /**
599      * Save the {@code Random} instance to a stream.
600      *
601      * @param  s the {@code ObjectOutputStream} to which data is written
602      *
603      * @throws IOException if an I/O error occurs
604      */
605     @java.io.Serial
writeObject(ObjectOutputStream s)606     private synchronized void writeObject(ObjectOutputStream s)
607             throws IOException {
608 
609         // set the values of the Serializable fields
610         ObjectOutputStream.PutField fields = s.putFields();
611 
612         // The seed is serialized as a long for historical reasons.
613         fields.put("seed", seed.get());
614         fields.put("nextNextGaussian", nextNextGaussian);
615         fields.put("haveNextNextGaussian", haveNextNextGaussian);
616 
617         // save them
618         s.writeFields();
619     }
620 
621     // Support for resetting seed while deserializing
622     private static final Unsafe unsafe = Unsafe.getUnsafe();
623     private static final long seedOffset;
624     static {
625         try {
626             seedOffset = unsafe.objectFieldOffset
627                     (Random.class.getDeclaredField("seed"));
628         } catch (Exception ex) { throw new Error(ex); }
629     }
resetSeed(long seedVal)630     private void resetSeed(long seedVal) {
631         unsafe.putReferenceVolatile(this, seedOffset, new AtomicLong(seedVal));
632     }
633 
634     /**
635      * Returns a stream producing the given {@code streamSize} number of
636      * pseudorandom {@code int} values.
637      *
638      * <p>A pseudorandom {@code int} value is generated as if it's the result of
639      * calling the method {@link #nextInt()}.
640      *
641      * @param streamSize the number of values to generate
642      * @return a stream of pseudorandom {@code int} values
643      * @throws IllegalArgumentException if {@code streamSize} is
644      *         less than zero
645      * @since 1.8
646      */
647     @Override
ints(long streamSize)648     public IntStream ints(long streamSize) {
649         return AbstractSpliteratorGenerator.ints(this, streamSize);
650     }
651 
652     /**
653      * Returns an effectively unlimited stream of pseudorandom {@code int}
654      * values.
655      *
656      * <p>A pseudorandom {@code int} value is generated as if it's the result of
657      * calling the method {@link #nextInt()}.
658      *
659      * @implNote This method is implemented to be equivalent to {@code
660      * ints(Long.MAX_VALUE)}.
661      *
662      * @return a stream of pseudorandom {@code int} values
663      * @since 1.8
664      */
665     @Override
ints()666     public IntStream ints() {
667         // Android-changed: keep old behaviour for apps targeting already released
668         // platforms.
669         // return AbstractSpliteratorGenerator.ints(this);
670         if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM &&
671             Compatibility.isChangeEnabled(STREAM_INT_DIFFERS_FROM_NEXT_INT)) {
672             return AbstractSpliteratorGenerator.ints(this);
673         } else {
674             return IntStream.generate(this::nextInt);
675         }
676     }
677 
678     // Android-added: implementation specified in ints(long, int, int) javadoc.
boundedNextInt(int origin, int bound)679     private int boundedNextInt(int origin, int bound) {
680         int n = bound - origin;
681         if (n > 0) {
682             return nextInt(n) + origin;
683         } else {  // range not representable as int
684             int r;
685             do {
686                 r = nextInt();
687             } while (r < origin || r >= bound);
688             return r;
689         }
690     }
691 
692     /**
693      * Returns a stream producing the given {@code streamSize} number
694      * of pseudorandom {@code int} values, each conforming to the given
695      * origin (inclusive) and bound (exclusive).
696      *
697      * <p>A pseudorandom {@code int} value is generated as if it's the result of
698      * calling the following method with the origin and bound:
699      * <pre> {@code
700      * int nextInt(int origin, int bound) {
701      *   int n = bound - origin;
702      *   if (n > 0) {
703      *     return nextInt(n) + origin;
704      *   }
705      *   else {  // range not representable as int
706      *     int r;
707      *     do {
708      *       r = nextInt();
709      *     } while (r < origin || r >= bound);
710      *     return r;
711      *   }
712      * }}</pre>
713      *
714      * @param streamSize the number of values to generate
715      * @param randomNumberOrigin the origin (inclusive) of each random value
716      * @param randomNumberBound the bound (exclusive) of each random value
717      * @return a stream of pseudorandom {@code int} values,
718      *         each with the given origin (inclusive) and bound (exclusive)
719      * @throws IllegalArgumentException if {@code streamSize} is
720      *         less than zero, or {@code randomNumberOrigin}
721      *         is greater than or equal to {@code randomNumberBound}
722      * @since 1.8
723      */
724     @Override
ints(long streamSize, int randomNumberOrigin, int randomNumberBound)725     public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) {
726         // Android-changed: keep old behaviour for apps targeting already released
727         // platforms.
728         // return AbstractSpliteratorGenerator.ints(this, streamSize, randomNumberOrigin, randomNumberBound);
729         if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM &&
730             Compatibility.isChangeEnabled(STREAM_INT_DIFFERS_FROM_NEXT_INT)) {
731             return AbstractSpliteratorGenerator.ints(this, streamSize, randomNumberOrigin, randomNumberBound);
732         } else {
733             RandomSupport.checkStreamSize(streamSize);
734             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
735             return IntStream
736                 .generate(() -> boundedNextInt(randomNumberOrigin, randomNumberBound))
737                 .limit(streamSize);
738         }
739     }
740 
741     /**
742      * Returns an effectively unlimited stream of pseudorandom {@code
743      * int} values, each conforming to the given origin (inclusive) and bound
744      * (exclusive).
745      *
746      * <p>A pseudorandom {@code int} value is generated as if it's the result of
747      * calling the following method with the origin and bound:
748      * <pre> {@code
749      * int nextInt(int origin, int bound) {
750      *   int n = bound - origin;
751      *   if (n > 0) {
752      *     return nextInt(n) + origin;
753      *   }
754      *   else {  // range not representable as int
755      *     int r;
756      *     do {
757      *       r = nextInt();
758      *     } while (r < origin || r >= bound);
759      *     return r;
760      *   }
761      * }}</pre>
762      *
763      * @implNote This method is implemented to be equivalent to {@code
764      * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
765      *
766      * @param randomNumberOrigin the origin (inclusive) of each random value
767      * @param randomNumberBound the bound (exclusive) of each random value
768      * @return a stream of pseudorandom {@code int} values,
769      *         each with the given origin (inclusive) and bound (exclusive)
770      * @throws IllegalArgumentException if {@code randomNumberOrigin}
771      *         is greater than or equal to {@code randomNumberBound}
772      * @since 1.8
773      */
774     @Override
ints(int randomNumberOrigin, int randomNumberBound)775     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
776         // Android-changed: keep old behaviour for apps targeting already released
777         // platforms.
778         // return AbstractSpliteratorGenerator.ints(this, randomNumberOrigin, randomNumberBound);
779         if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM &&
780             Compatibility.isChangeEnabled(STREAM_INT_DIFFERS_FROM_NEXT_INT)) {
781             return AbstractSpliteratorGenerator.ints(this, randomNumberOrigin, randomNumberBound);
782         } else {
783             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
784             return IntStream.generate(() -> boundedNextInt(randomNumberOrigin, randomNumberBound));
785         }
786     }
787 
788     /**
789      * Returns a stream producing the given {@code streamSize} number of
790      * pseudorandom {@code long} values.
791      *
792      * <p>A pseudorandom {@code long} value is generated as if it's the result
793      * of calling the method {@link #nextLong()}.
794      *
795      * @param streamSize the number of values to generate
796      * @return a stream of pseudorandom {@code long} values
797      * @throws IllegalArgumentException if {@code streamSize} is
798      *         less than zero
799      * @since 1.8
800      */
801     @Override
longs(long streamSize)802     public LongStream longs(long streamSize) {
803         return AbstractSpliteratorGenerator.longs(this, streamSize);
804     }
805 
806     /**
807      * Returns an effectively unlimited stream of pseudorandom {@code long}
808      * values.
809      *
810      * <p>A pseudorandom {@code long} value is generated as if it's the result
811      * of calling the method {@link #nextLong()}.
812      *
813      * @implNote This method is implemented to be equivalent to {@code
814      * longs(Long.MAX_VALUE)}.
815      *
816      * @return a stream of pseudorandom {@code long} values
817      * @since 1.8
818      */
819     @Override
longs()820     public LongStream longs() {
821         return AbstractSpliteratorGenerator.longs(this);
822     }
823 
824     /**
825      * Returns a stream producing the given {@code streamSize} number of
826      * pseudorandom {@code long}, each conforming to the given origin
827      * (inclusive) and bound (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      * @param streamSize the number of values to generate
852      * @param randomNumberOrigin the origin (inclusive) of each random value
853      * @param randomNumberBound the bound (exclusive) of each random value
854      * @return a stream of pseudorandom {@code long} values,
855      *         each with the given origin (inclusive) and bound (exclusive)
856      * @throws IllegalArgumentException if {@code streamSize} is
857      *         less than zero, or {@code randomNumberOrigin}
858      *         is greater than or equal to {@code randomNumberBound}
859      * @since 1.8
860      */
861     @Override
longs(long streamSize, long randomNumberOrigin, long randomNumberBound)862     public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) {
863         return AbstractSpliteratorGenerator.longs(this, streamSize, randomNumberOrigin, randomNumberBound);
864     }
865 
866     /**
867      * Returns an effectively unlimited stream of pseudorandom {@code
868      * long} values, each conforming to the given origin (inclusive) and bound
869      * (exclusive).
870      *
871      * <p>A pseudorandom {@code long} value is generated as if it's the result
872      * of calling the following method with the origin and bound:
873      * <pre> {@code
874      * long nextLong(long origin, long bound) {
875      *   long r = nextLong();
876      *   long n = bound - origin, m = n - 1;
877      *   if ((n & m) == 0L)  // power of two
878      *     r = (r & m) + origin;
879      *   else if (n > 0L) {  // reject over-represented candidates
880      *     for (long u = r >>> 1;            // ensure nonnegative
881      *          u + m - (r = u % n) < 0L;    // rejection check
882      *          u = nextLong() >>> 1) // retry
883      *         ;
884      *     r += origin;
885      *   }
886      *   else {              // range not representable as long
887      *     while (r < origin || r >= bound)
888      *       r = nextLong();
889      *   }
890      *   return r;
891      * }}</pre>
892      *
893      * @implNote This method is implemented to be equivalent to {@code
894      * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
895      *
896      * @param randomNumberOrigin the origin (inclusive) of each random value
897      * @param randomNumberBound the bound (exclusive) of each random value
898      * @return a stream of pseudorandom {@code long} values,
899      *         each with the given origin (inclusive) and bound (exclusive)
900      * @throws IllegalArgumentException if {@code randomNumberOrigin}
901      *         is greater than or equal to {@code randomNumberBound}
902      * @since 1.8
903      */
904     @Override
longs(long randomNumberOrigin, long randomNumberBound)905     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
906         return AbstractSpliteratorGenerator.longs(this, randomNumberOrigin, randomNumberBound);
907     }
908 
909     /**
910      * Returns a stream producing the given {@code streamSize} number of
911      * pseudorandom {@code double} values, each between zero
912      * (inclusive) and one (exclusive).
913      *
914      * <p>A pseudorandom {@code double} value is generated as if it's the result
915      * of calling the method {@link #nextDouble()}.
916      *
917      * @param streamSize the number of values to generate
918      * @return a stream of {@code double} values
919      * @throws IllegalArgumentException if {@code streamSize} is
920      *         less than zero
921      * @since 1.8
922      */
923     @Override
doubles(long streamSize)924     public DoubleStream doubles(long streamSize) {
925         return AbstractSpliteratorGenerator.doubles(this, streamSize);
926     }
927 
928     /**
929      * Returns an effectively unlimited stream of pseudorandom {@code
930      * double} values, each between zero (inclusive) and one
931      * (exclusive).
932      *
933      * <p>A pseudorandom {@code double} value is generated as if it's the result
934      * of calling the method {@link #nextDouble()}.
935      *
936      * @implNote This method is implemented to be equivalent to {@code
937      * doubles(Long.MAX_VALUE)}.
938      *
939      * @return a stream of pseudorandom {@code double} values
940      * @since 1.8
941      */
942     @Override
doubles()943     public DoubleStream doubles() {
944         return AbstractSpliteratorGenerator.doubles(this);
945     }
946 
947    /**
948      * Returns a stream producing the given {@code streamSize} number of
949      * pseudorandom {@code double} values, each conforming to the given origin
950      * (inclusive) and bound (exclusive).
951      *
952      * <p>A pseudorandom {@code double} value is generated as if it's the result
953      * of calling the following method with the origin and bound:
954      * <pre> {@code
955      * double nextDouble(double origin, double bound) {
956      *   double r = nextDouble();
957      *   r = r * (bound - origin) + origin;
958      *   if (r >= bound) // correct for rounding
959      *     r = Math.nextDown(bound);
960      *   return r;
961      * }}</pre>
962      *
963      * @param streamSize the number of values to generate
964      * @param randomNumberOrigin the origin (inclusive) of each random value
965      * @param randomNumberBound the bound (exclusive) of each random value
966      * @return a stream of pseudorandom {@code double} values,
967      *         each with the given origin (inclusive) and bound (exclusive)
968      * @throws IllegalArgumentException if {@code streamSize} is less than zero,
969      *         or {@code randomNumberOrigin} is not finite,
970      *         or {@code randomNumberBound} is not finite, or {@code randomNumberOrigin}
971      *         is greater than or equal to {@code randomNumberBound}
972      * @since 1.8
973      */
974     @Override
doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)975     public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) {
976         return AbstractSpliteratorGenerator.doubles(this, streamSize, randomNumberOrigin, randomNumberBound);
977     }
978 
979     /**
980      * Returns an effectively unlimited stream of pseudorandom {@code
981      * double} values, each conforming to the given origin (inclusive) and bound
982      * (exclusive).
983      *
984      * <p>A pseudorandom {@code double} value is generated as if it's the result
985      * of calling the following method with the origin and bound:
986      * <pre> {@code
987      * double nextDouble(double origin, double bound) {
988      *   double r = nextDouble();
989      *   r = r * (bound - origin) + origin;
990      *   if (r >= bound) // correct for rounding
991      *     r = Math.nextDown(bound);
992      *   return r;
993      * }}</pre>
994      *
995      * @implNote This method is implemented to be equivalent to {@code
996      * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
997      *
998      * @param randomNumberOrigin the origin (inclusive) of each random value
999      * @param randomNumberBound the bound (exclusive) of each random value
1000      * @return a stream of pseudorandom {@code double} values,
1001      *         each with the given origin (inclusive) and bound (exclusive)
1002      * @throws IllegalArgumentException if {@code randomNumberOrigin}
1003      *         is greater than or equal to {@code randomNumberBound}
1004      * @since 1.8
1005      */
1006     @Override
doubles(double randomNumberOrigin, double randomNumberBound)1007     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
1008         return AbstractSpliteratorGenerator.doubles(this, randomNumberOrigin, randomNumberBound);
1009     }
1010 }
1011