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