ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.27
Committed: Tue Sep 21 17:00:45 2010 UTC (14 years ago) by jsr166
Branch: MAIN
Changes since 1.26: +1 -1 lines
Log Message:
@exception => @throws

File Contents

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