1 /*
   2  * Copyright (c) 1995, 2011, 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.stream.DoubleStream;
  30 import java.util.stream.IntStream;
  31 import java.util.stream.LongStream;
  32 
  33 import sun.misc.Unsafe;
  34 
  35 /**
  36  * An instance of this class is used to generate a stream of
  37  * pseudorandom numbers. The class uses a 48-bit seed, which is
  38  * modified using a linear congruential formula. (See Donald Knuth,
  39  * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
  40  * <p>
  41  * If two instances of {@code Random} are created with the same
  42  * seed, and the same sequence of method calls is made for each, they
  43  * will generate and return identical sequences of numbers. In order to
  44  * guarantee this property, particular algorithms are specified for the
  45  * class {@code Random}. Java implementations must use all the algorithms
  46  * shown here for the class {@code Random}, for the sake of absolute
  47  * portability of Java code. However, subclasses of class {@code Random}
  48  * are permitted to use other algorithms, so long as they adhere to the
  49  * general contracts for all the methods.
  50  * <p>
  51  * The algorithms implemented by class {@code Random} use a
  52  * {@code protected} utility method that on each invocation can supply
  53  * up to 32 pseudorandomly generated bits.
  54  * <p>
  55  * Many applications will find the method {@link Math#random} simpler to use.
  56  *
  57  * <p>Instances of {@code java.util.Random} are threadsafe.
  58  * However, the concurrent use of the same {@code java.util.Random}
  59  * instance across threads may encounter contention and consequent
  60  * poor performance. Consider instead using
  61  * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
  62  * designs.
  63  *
  64  * <p>Instances of {@code java.util.Random} are not cryptographically
  65  * secure.  Consider instead using {@link java.security.SecureRandom} to
  66  * get a cryptographically secure pseudo-random number generator for use
  67  * by security-sensitive applications.
  68  *
  69  * @author  Frank Yellin
  70  * @since   1.0
  71  */
  72 public
  73 class Random implements java.io.Serializable {
  74     /** use serialVersionUID from JDK 1.1 for interoperability */
  75     static final long serialVersionUID = 3905348978240129619L;
  76 
  77     /**
  78      * The internal state associated with this pseudorandom number generator.
  79      * (The specs for the methods in this class describe the ongoing
  80      * computation of this value.)
  81      */
  82     private final AtomicLong seed;
  83 
  84     private static final long multiplier = 0x5DEECE66DL;
  85     private static final long addend = 0xBL;
  86     private static final long mask = (1L << 48) - 1;
  87 
  88     /**
  89      * Creates a new random number generator. This constructor sets
  90      * the seed of the random number generator to a value very likely
  91      * to be distinct from any other invocation of this constructor.
  92      */
  93     public Random() {
  94         this(seedUniquifier() ^ System.nanoTime());
  95     }
  96 
  97     private static long seedUniquifier() {
  98         // L'Ecuyer, "Tables of Linear Congruential Generators of
  99         // Different Sizes and Good Lattice Structure", 1999
 100         for (;;) {
 101             long current = seedUniquifier.get();
 102             long next = current * 181783497276652981L;
 103             if (seedUniquifier.compareAndSet(current, next))
 104                 return next;
 105         }
 106     }
 107 
 108     private static final AtomicLong seedUniquifier
 109         = new AtomicLong(8682522807148012L);
 110 
 111     /**
 112      * Creates a new random number generator using a single {@code long} seed.
 113      * The seed is the initial value of the internal state of the pseudorandom
 114      * number generator which is maintained by method {@link #next}.
 115      *
 116      * <p>The invocation {@code new Random(seed)} is equivalent to:
 117      *  <pre> {@code
 118      * Random rnd = new Random();
 119      * rnd.setSeed(seed);}</pre>
 120      *
 121      * @param seed the initial seed
 122      * @see   #setSeed(long)
 123      */
 124     public Random(long seed) {
 125         if (getClass() == Random.class)
 126             this.seed = new AtomicLong(initialScramble(seed));
 127         else {
 128             // subclass might have overriden setSeed
 129             this.seed = new AtomicLong();
 130             setSeed(seed);
 131         }
 132     }
 133 
 134     private static long initialScramble(long seed) {
 135         return (seed ^ multiplier) & mask;
 136     }
 137 
 138     /**
 139      * Sets the seed of this random number generator using a single
 140      * {@code long} seed. The general contract of {@code setSeed} is
 141      * that it alters the state of this random number generator object
 142      * so as to be in exactly the same state as if it had just been
 143      * created with the argument {@code seed} as a seed. The method
 144      * {@code setSeed} is implemented by class {@code Random} by
 145      * atomically updating the seed to
 146      *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
 147      * and clearing the {@code haveNextNextGaussian} flag used by {@link
 148      * #nextGaussian}.
 149      *
 150      * <p>The implementation of {@code setSeed} by class {@code Random}
 151      * happens to use only 48 bits of the given seed. In general, however,
 152      * an overriding method may use all 64 bits of the {@code long}
 153      * argument as a seed value.
 154      *
 155      * @param seed the initial seed
 156      */
 157     synchronized public void setSeed(long seed) {
 158         this.seed.set(initialScramble(seed));
 159         haveNextNextGaussian = false;
 160     }
 161 
 162     /**
 163      * Generates the next pseudorandom number. Subclasses should
 164      * override this, as this is used by all other methods.
 165      *
 166      * <p>The general contract of {@code next} is that it returns an
 167      * {@code int} value and if the argument {@code bits} is between
 168      * {@code 1} and {@code 32} (inclusive), then that many low-order
 169      * bits of the returned value will be (approximately) independently
 170      * chosen bit values, each of which is (approximately) equally
 171      * likely to be {@code 0} or {@code 1}. The method {@code next} is
 172      * implemented by class {@code Random} by atomically updating the seed to
 173      *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
 174      * and returning
 175      *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
 176      *
 177      * This is a linear congruential pseudorandom number generator, as
 178      * defined by D. H. Lehmer and described by Donald E. Knuth in
 179      * <i>The Art of Computer Programming,</i> Volume 3:
 180      * <i>Seminumerical Algorithms</i>, section 3.2.1.
 181      *
 182      * @param  bits random bits
 183      * @return the next pseudorandom value from this random number
 184      *         generator's sequence
 185      * @since  1.1
 186      */
 187     protected int next(int bits) {
 188         long oldseed, nextseed;
 189         AtomicLong seed = this.seed;
 190         do {
 191             oldseed = seed.get();
 192             nextseed = (oldseed * multiplier + addend) & mask;
 193         } while (!seed.compareAndSet(oldseed, nextseed));
 194         return (int)(nextseed >>> (48 - bits));
 195     }
 196 
 197     /**
 198      * Generates random bytes and places them into a user-supplied
 199      * byte array.  The number of random bytes produced is equal to
 200      * the length of the byte array.
 201      *
 202      * <p>The method {@code nextBytes} is implemented by class {@code Random}
 203      * as if by:
 204      *  <pre> {@code
 205      * public void nextBytes(byte[] bytes) {
 206      *   for (int i = 0; i < bytes.length; )
 207      *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
 208      *          n-- > 0; rnd >>= 8)
 209      *       bytes[i++] = (byte)rnd;
 210      * }}</pre>
 211      *
 212      * @param  bytes the byte array to fill with random bytes
 213      * @throws NullPointerException if the byte array is null
 214      * @since  1.1
 215      */
 216     public void nextBytes(byte[] bytes) {
 217         for (int i = 0, len = bytes.length; i < len; )
 218             for (int rnd = nextInt(),
 219                      n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
 220                  n-- > 0; rnd >>= Byte.SIZE)
 221                 bytes[i++] = (byte)rnd;
 222     }
 223 
 224     /**
 225      * Returns the next pseudorandom, uniformly distributed {@code int}
 226      * value from this random number generator's sequence. The general
 227      * contract of {@code nextInt} is that one {@code int} value is
 228      * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
 229      * </sup></font> possible {@code int} values are produced with
 230      * (approximately) equal probability.
 231      *
 232      * <p>The method {@code nextInt} is implemented by class {@code Random}
 233      * as if by:
 234      *  <pre> {@code
 235      * public int nextInt() {
 236      *   return next(32);
 237      * }}</pre>
 238      *
 239      * @return the next pseudorandom, uniformly distributed {@code int}
 240      *         value from this random number generator's sequence
 241      */
 242     public int nextInt() {
 243         return next(32);
 244     }
 245 
 246     /**
 247      * Returns a pseudorandom, uniformly distributed {@code int} value
 248      * between 0 (inclusive) and the specified value (exclusive), drawn from
 249      * this random number generator's sequence.  The general contract of
 250      * {@code nextInt} is that one {@code int} value in the specified range
 251      * is pseudorandomly generated and returned.  All {@code n} possible
 252      * {@code int} values are produced with (approximately) equal
 253      * probability.  The method {@code nextInt(int n)} is implemented by
 254      * class {@code Random} as if by:
 255      *  <pre> {@code
 256      * public int nextInt(int n) {
 257      *   if (n <= 0)
 258      *     throw new IllegalArgumentException("n must be positive");
 259      *
 260      *   if ((n & -n) == n)  // i.e., n is a power of 2
 261      *     return (int)((n * (long)next(31)) >> 31);
 262      *
 263      *   int bits, val;
 264      *   do {
 265      *       bits = next(31);
 266      *       val = bits % n;
 267      *   } while (bits - val + (n-1) < 0);
 268      *   return val;
 269      * }}</pre>
 270      *
 271      * <p>The hedge "approximately" is used in the foregoing description only
 272      * because the next method is only approximately an unbiased source of
 273      * independently chosen bits.  If it were a perfect source of randomly
 274      * chosen bits, then the algorithm shown would choose {@code int}
 275      * values from the stated range with perfect uniformity.
 276      * <p>
 277      * The algorithm is slightly tricky.  It rejects values that would result
 278      * in an uneven distribution (due to the fact that 2^31 is not divisible
 279      * by n). The probability of a value being rejected depends on n.  The
 280      * worst case is n=2^30+1, for which the probability of a reject is 1/2,
 281      * and the expected number of iterations before the loop terminates is 2.
 282      * <p>
 283      * The algorithm treats the case where n is a power of two specially: it
 284      * returns the correct number of high-order bits from the underlying
 285      * pseudo-random number generator.  In the absence of special treatment,
 286      * the correct number of <i>low-order</i> bits would be returned.  Linear
 287      * congruential pseudo-random number generators such as the one
 288      * implemented by this class are known to have short periods in the
 289      * sequence of values of their low-order bits.  Thus, this special case
 290      * greatly increases the length of the sequence of values returned by
 291      * successive calls to this method if n is a small power of two.
 292      *
 293      * @param n the bound on the random number to be returned.  Must be
 294      *        positive.
 295      * @return the next pseudorandom, uniformly distributed {@code int}
 296      *         value between {@code 0} (inclusive) and {@code n} (exclusive)
 297      *         from this random number generator's sequence
 298      * @throws IllegalArgumentException if n is not positive
 299      * @since 1.2
 300      */
 301 
 302     public int nextInt(int n) {
 303         if (n <= 0)
 304             throw new IllegalArgumentException("n must be positive");
 305 
 306         if ((n & -n) == n)  // i.e., n is a power of 2
 307             return (int)((n * (long)next(31)) >> 31);
 308 
 309         int bits, val;
 310         do {
 311             bits = next(31);
 312             val = bits % n;
 313         } while (bits - val + (n-1) < 0);
 314         return val;
 315     }
 316 
 317     /**
 318      * Returns the next pseudorandom, uniformly distributed {@code long}
 319      * value from this random number generator's sequence. The general
 320      * contract of {@code nextLong} is that one {@code long} value is
 321      * pseudorandomly generated and returned.
 322      *
 323      * <p>The method {@code nextLong} is implemented by class {@code Random}
 324      * as if by:
 325      *  <pre> {@code
 326      * public long nextLong() {
 327      *   return ((long)next(32) << 32) + next(32);
 328      * }}</pre>
 329      *
 330      * Because class {@code Random} uses a seed with only 48 bits,
 331      * this algorithm will not return all possible {@code long} values.
 332      *
 333      * @return the next pseudorandom, uniformly distributed {@code long}
 334      *         value from this random number generator's sequence
 335      */
 336     public long nextLong() {
 337         // it's okay that the bottom word remains signed.
 338         return ((long)(next(32)) << 32) + next(32);
 339     }
 340 
 341     /**
 342      * Returns the next pseudorandom, uniformly distributed
 343      * {@code boolean} value from this random number generator's
 344      * sequence. The general contract of {@code nextBoolean} is that one
 345      * {@code boolean} value is pseudorandomly generated and returned.  The
 346      * values {@code true} and {@code false} are produced with
 347      * (approximately) equal probability.
 348      *
 349      * <p>The method {@code nextBoolean} is implemented by class {@code Random}
 350      * as if by:
 351      *  <pre> {@code
 352      * public boolean nextBoolean() {
 353      *   return next(1) != 0;
 354      * }}</pre>
 355      *
 356      * @return the next pseudorandom, uniformly distributed
 357      *         {@code boolean} value from this random number generator's
 358      *         sequence
 359      * @since 1.2
 360      */
 361     public boolean nextBoolean() {
 362         return next(1) != 0;
 363     }
 364 
 365     /**
 366      * Returns the next pseudorandom, uniformly distributed {@code float}
 367      * value between {@code 0.0} and {@code 1.0} from this random
 368      * number generator's sequence.
 369      *
 370      * <p>The general contract of {@code nextFloat} is that one
 371      * {@code float} value, chosen (approximately) uniformly from the
 372      * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
 373      * pseudorandomly generated and returned. All 2<font
 374      * size="-1"><sup>24</sup></font> possible {@code float} values
 375      * of the form <i>m&nbsp;x&nbsp</i>2<font
 376      * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
 377      * integer less than 2<font size="-1"><sup>24</sup> </font>, are
 378      * produced with (approximately) equal probability.
 379      *
 380      * <p>The method {@code nextFloat} is implemented by class {@code Random}
 381      * as if by:
 382      *  <pre> {@code
 383      * public float nextFloat() {
 384      *   return next(24) / ((float)(1 << 24));
 385      * }}</pre>
 386      *
 387      * <p>The hedge "approximately" is used in the foregoing description only
 388      * because the next method is only approximately an unbiased source of
 389      * independently chosen bits. If it were a perfect source of randomly
 390      * chosen bits, then the algorithm shown would choose {@code float}
 391      * values from the stated range with perfect uniformity.<p>
 392      * [In early versions of Java, the result was incorrectly calculated as:
 393      *  <pre> {@code
 394      *   return next(30) / ((float)(1 << 30));}</pre>
 395      * This might seem to be equivalent, if not better, but in fact it
 396      * introduced a slight nonuniformity because of the bias in the rounding
 397      * of floating-point numbers: it was slightly more likely that the
 398      * low-order bit of the significand would be 0 than that it would be 1.]
 399      *
 400      * @return the next pseudorandom, uniformly distributed {@code float}
 401      *         value between {@code 0.0} and {@code 1.0} from this
 402      *         random number generator's sequence
 403      */
 404     public float nextFloat() {
 405         return next(24) / ((float)(1 << 24));
 406     }
 407 
 408     /**
 409      * Returns the next pseudorandom, uniformly distributed
 410      * {@code double} value between {@code 0.0} and
 411      * {@code 1.0} from this random number generator's sequence.
 412      *
 413      * <p>The general contract of {@code nextDouble} is that one
 414      * {@code double} value, chosen (approximately) uniformly from the
 415      * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
 416      * pseudorandomly generated and returned.
 417      *
 418      * <p>The method {@code nextDouble} is implemented by class {@code Random}
 419      * as if by:
 420      *  <pre> {@code
 421      * public double nextDouble() {
 422      *   return (((long)next(26) << 27) + next(27))
 423      *     / (double)(1L << 53);
 424      * }}</pre>
 425      *
 426      * <p>The hedge "approximately" is used in the foregoing description only
 427      * because the {@code next} method is only approximately an unbiased
 428      * source of independently chosen bits. If it were a perfect source of
 429      * randomly chosen bits, then the algorithm shown would choose
 430      * {@code double} values from the stated range with perfect uniformity.
 431      * <p>[In early versions of Java, the result was incorrectly calculated as:
 432      *  <pre> {@code
 433      *   return (((long)next(27) << 27) + next(27))
 434      *     / (double)(1L << 54);}</pre>
 435      * This might seem to be equivalent, if not better, but in fact it
 436      * introduced a large nonuniformity because of the bias in the rounding
 437      * of floating-point numbers: it was three times as likely that the
 438      * low-order bit of the significand would be 0 than that it would be 1!
 439      * This nonuniformity probably doesn't matter much in practice, but we
 440      * strive for perfection.]
 441      *
 442      * @return the next pseudorandom, uniformly distributed {@code double}
 443      *         value between {@code 0.0} and {@code 1.0} from this
 444      *         random number generator's sequence
 445      * @see Math#random
 446      */
 447     public double nextDouble() {
 448         return (((long)(next(26)) << 27) + next(27))
 449             / (double)(1L << 53);
 450     }
 451 
 452     private double nextNextGaussian;
 453     private boolean haveNextNextGaussian = false;
 454 
 455     /**
 456      * Returns the next pseudorandom, Gaussian ("normally") distributed
 457      * {@code double} value with mean {@code 0.0} and standard
 458      * deviation {@code 1.0} from this random number generator's sequence.
 459      * <p>
 460      * The general contract of {@code nextGaussian} is that one
 461      * {@code double} value, chosen from (approximately) the usual
 462      * normal distribution with mean {@code 0.0} and standard deviation
 463      * {@code 1.0}, is pseudorandomly generated and returned.
 464      *
 465      * <p>The method {@code nextGaussian} is implemented by class
 466      * {@code Random} as if by a threadsafe version of the following:
 467      *  <pre> {@code
 468      * private double nextNextGaussian;
 469      * private boolean haveNextNextGaussian = false;
 470      *
 471      * public double nextGaussian() {
 472      *   if (haveNextNextGaussian) {
 473      *     haveNextNextGaussian = false;
 474      *     return nextNextGaussian;
 475      *   } else {
 476      *     double v1, v2, s;
 477      *     do {
 478      *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
 479      *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
 480      *       s = v1 * v1 + v2 * v2;
 481      *     } while (s >= 1 || s == 0);
 482      *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
 483      *     nextNextGaussian = v2 * multiplier;
 484      *     haveNextNextGaussian = true;
 485      *     return v1 * multiplier;
 486      *   }
 487      * }}</pre>
 488      * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
 489      * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
 490      * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
 491      * section 3.4.1, subsection C, algorithm P. Note that it generates two
 492      * independent values at the cost of only one call to {@code StrictMath.log}
 493      * and one call to {@code StrictMath.sqrt}.
 494      *
 495      * @return the next pseudorandom, Gaussian ("normally") distributed
 496      *         {@code double} value with mean {@code 0.0} and
 497      *         standard deviation {@code 1.0} from this random number
 498      *         generator's sequence
 499      */
 500     synchronized public double nextGaussian() {
 501         // See Knuth, ACP, Section 3.4.1 Algorithm C.
 502         if (haveNextNextGaussian) {
 503             haveNextNextGaussian = false;
 504             return nextNextGaussian;
 505         } else {
 506             double v1, v2, s;
 507             do {
 508                 v1 = 2 * nextDouble() - 1; // between -1 and 1
 509                 v2 = 2 * nextDouble() - 1; // between -1 and 1
 510                 s = v1 * v1 + v2 * v2;
 511             } while (s >= 1 || s == 0);
 512             double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
 513             nextNextGaussian = v2 * multiplier;
 514             haveNextNextGaussian = true;
 515             return v1 * multiplier;
 516         }
 517     }
 518 
 519     /**
 520      * Returns a stream of pseudorandom, uniformly distributed
 521      * {@code integer} values from this random number generator's
 522      * sequence. Values are obtained as needed by calling
 523      * {@link #nextInt()}.
 524      *
 525      * @return an infinite stream of {@code integer} values
 526      * @since 1.8
 527      */
 528     public IntStream ints() {
 529         return IntStream.generate(this::nextInt);
 530     }
 531 
 532     /**
 533      * Returns a stream of pseudorandom, uniformly distributed
 534      * {@code long} values from this random number generator's
 535      * sequence. Values are obtained as needed by calling
 536      * {@link #nextLong()}.
 537      *
 538      * @return an infinite stream of {@code long} values
 539      * @since 1.8
 540      */
 541     public LongStream longs() {
 542         return LongStream.generate(this::nextLong);
 543     }
 544 
 545     /**
 546      * Returns a stream of pseudorandom, uniformly distributed
 547      * {@code double} values between {@code 0.0} and {@code 1.0}
 548      * from this random number generator's sequence. Values are
 549      * obtained as needed by calling {@link #nextDouble()}.
 550      *
 551      * @return an infinite stream of {@code double} values
 552      * @since 1.8
 553      */
 554     public DoubleStream doubles() {
 555         return DoubleStream.generate(this::nextDouble);
 556     }
 557 
 558     /**
 559      * Returns a stream of pseudorandom, Gaussian ("normally")
 560      * distributed {@code double} values with mean {@code 0.0}
 561      * and standard deviation {@code 1.0} from this random number
 562      * generator's sequence. Values are obtained as needed by
 563      * calling {@link #nextGaussian()}.
 564      *
 565      * @return an infinite stream of {@code double} values
 566      * @since 1.8
 567      */
 568     public DoubleStream gaussians() {
 569         return DoubleStream.generate(this::nextGaussian);
 570     }
 571 
 572     /**
 573      * Serializable fields for Random.
 574      *
 575      * @serialField    seed long
 576      *              seed for random computations
 577      * @serialField    nextNextGaussian double
 578      *              next Gaussian to be returned
 579      * @serialField      haveNextNextGaussian boolean
 580      *              nextNextGaussian is valid
 581      */
 582     private static final ObjectStreamField[] serialPersistentFields = {
 583         new ObjectStreamField("seed", Long.TYPE),
 584         new ObjectStreamField("nextNextGaussian", Double.TYPE),
 585         new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
 586     };
 587 
 588     /**
 589      * Reconstitute the {@code Random} instance from a stream (that is,
 590      * deserialize it).
 591      */
 592     private void readObject(java.io.ObjectInputStream s)
 593         throws java.io.IOException, ClassNotFoundException {
 594 
 595         ObjectInputStream.GetField fields = s.readFields();
 596 
 597         // The seed is read in as {@code long} for
 598         // historical reasons, but it is converted to an AtomicLong.
 599         long seedVal = fields.get("seed", -1L);
 600         if (seedVal < 0)
 601           throw new java.io.StreamCorruptedException(
 602                               "Random: invalid seed");
 603         resetSeed(seedVal);
 604         nextNextGaussian = fields.get("nextNextGaussian", 0.0);
 605         haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
 606     }
 607 
 608     /**
 609      * Save the {@code Random} instance to a stream.
 610      */
 611     synchronized private void writeObject(ObjectOutputStream s)
 612         throws IOException {
 613 
 614         // set the values of the Serializable fields
 615         ObjectOutputStream.PutField fields = s.putFields();
 616 
 617         // The seed is serialized as a long for historical reasons.
 618         fields.put("seed", seed.get());
 619         fields.put("nextNextGaussian", nextNextGaussian);
 620         fields.put("haveNextNextGaussian", haveNextNextGaussian);
 621 
 622         // save them
 623         s.writeFields();
 624     }
 625 
 626     // Support for resetting seed while deserializing
 627     private static final Unsafe unsafe = Unsafe.getUnsafe();
 628     private static final long seedOffset;
 629     static {
 630         try {
 631             seedOffset = unsafe.objectFieldOffset
 632                 (Random.class.getDeclaredField("seed"));
 633         } catch (Exception ex) { throw new Error(ex); }
 634     }
 635     private void resetSeed(long seedVal) {
 636         unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
 637     }
 638 }