ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.33
Committed: Wed Jan 16 19:02:12 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.32: +0 -0 lines
State: FILE REMOVED
Log Message:
Rely on openjdk version

File Contents

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