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.IntStream; |
30 |
import java.util.stream.Streams; |
31 |
|
32 |
import sun.misc.Unsafe; |
33 |
|
34 |
/** |
35 |
* 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 |
* <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.) |
39 |
* <p> |
40 |
* If two instances of {@code Random} are created with the same |
41 |
* 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 |
* 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 |
* are permitted to use other algorithms, so long as they adhere to the |
48 |
* general contracts for all the methods. |
49 |
* <p> |
50 |
* The algorithms implemented by class {@code Random} use a |
51 |
* {@code protected} utility method that on each invocation can supply |
52 |
* up to 32 pseudorandomly generated bits. |
53 |
* <p> |
54 |
* Many applications will find the method {@link Math#random} simpler to use. |
55 |
* |
56 |
* <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 |
* @author Frank Yellin |
69 |
* @since 1.0 |
70 |
*/ |
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 |
private final AtomicLong seed; |
82 |
|
83 |
private static final long multiplier = 0x5DEECE66DL; |
84 |
private static final long addend = 0xBL; |
85 |
private static final long mask = (1L << 48) - 1; |
86 |
|
87 |
/** |
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 |
*/ |
92 |
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 |
|
110 |
/** |
111 |
* 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 |
* |
120 |
* @param seed the initial seed |
121 |
* @see #setSeed(long) |
122 |
*/ |
123 |
public Random(long seed) { |
124 |
if (getClass() == Random.class) |
125 |
this.seed = new AtomicLong(initialScramble(seed)); |
126 |
else { |
127 |
// subclass might have overriden setSeed |
128 |
this.seed = new AtomicLong(); |
129 |
setSeed(seed); |
130 |
} |
131 |
} |
132 |
|
133 |
private static long initialScramble(long seed) { |
134 |
return (seed ^ multiplier) & mask; |
135 |
} |
136 |
|
137 |
/** |
138 |
* Sets the seed of this random number generator using a single |
139 |
* {@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 |
* |
154 |
* @param seed the initial seed |
155 |
*/ |
156 |
synchronized public void setSeed(long seed) { |
157 |
this.seed.set(initialScramble(seed)); |
158 |
haveNextNextGaussian = false; |
159 |
} |
160 |
|
161 |
/** |
162 |
* 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 |
*/ |
186 |
protected int next(int bits) { |
187 |
long oldseed, nextseed; |
188 |
AtomicLong seed = this.seed; |
189 |
do { |
190 |
oldseed = seed.get(); |
191 |
nextseed = (oldseed * multiplier + addend) & mask; |
192 |
} while (!seed.compareAndSet(oldseed, nextseed)); |
193 |
return (int)(nextseed >>> (48 - bits)); |
194 |
} |
195 |
|
196 |
/** |
197 |
* Generates random bytes and places them into a user-supplied |
198 |
* byte array. The number of random bytes produced is equal to |
199 |
* the length of the byte array. |
200 |
* |
201 |
* <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 |
*/ |
215 |
public void nextBytes(byte[] bytes) { |
216 |
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 |
} |
222 |
|
223 |
/** |
224 |
* Returns the next pseudorandom, uniformly distributed {@code int} |
225 |
* value from this random number generator's sequence. The general |
226 |
* contract of {@code nextInt} is that one {@code int} value is |
227 |
* pseudorandomly generated and returned. All 2<font size="-1"><sup>32 |
228 |
* </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 |
* |
238 |
* @return the next pseudorandom, uniformly distributed {@code int} |
239 |
* value from this random number generator's sequence |
240 |
*/ |
241 |
public int nextInt() { |
242 |
return next(32); |
243 |
} |
244 |
|
245 |
/** |
246 |
* Returns a pseudorandom, uniformly distributed {@code int} value |
247 |
* between 0 (inclusive) and the specified value (exclusive), drawn from |
248 |
* this random number generator's sequence. The general contract of |
249 |
* {@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 |
* public int nextInt(int n) { |
256 |
* 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 |
* |
262 |
* 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 |
* |
270 |
* <p>The hedge "approximately" is used in the foregoing description only |
271 |
* because the next method is only approximately an unbiased source of |
272 |
* independently chosen bits. If it were a perfect source of randomly |
273 |
* chosen bits, then the algorithm shown would choose {@code int} |
274 |
* 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 |
* positive. |
294 |
* @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 |
* @throws IllegalArgumentException if n is not positive |
298 |
* @since 1.2 |
299 |
*/ |
300 |
|
301 |
public int nextInt(int n) { |
302 |
if (n <= 0) |
303 |
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 |
} while (bits - val + (n-1) < 0); |
313 |
return val; |
314 |
} |
315 |
|
316 |
/** |
317 |
* Returns the next pseudorandom, uniformly distributed {@code long} |
318 |
* value from this random number generator's sequence. The general |
319 |
* 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 |
* public long nextLong() { |
326 |
* return ((long)next(32) << 32) + next(32); |
327 |
* }}</pre> |
328 |
* |
329 |
* 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 |
*/ |
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 |
* {@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 |
* sequence |
358 |
* @since 1.2 |
359 |
*/ |
360 |
public boolean nextBoolean() { |
361 |
return next(1) != 0; |
362 |
} |
363 |
|
364 |
/** |
365 |
* 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 x </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 |
* public float nextFloat() { |
383 |
* return next(24) / ((float)(1 << 24)); |
384 |
* }}</pre> |
385 |
* |
386 |
* <p>The hedge "approximately" is used in the foregoing description only |
387 |
* because the next method is only approximately an unbiased source of |
388 |
* independently chosen bits. If it were a perfect source of randomly |
389 |
* chosen bits, then the algorithm shown would choose {@code float} |
390 |
* values from the stated range with perfect uniformity.<p> |
391 |
* [In early versions of Java, the result was incorrectly calculated as: |
392 |
* <pre> {@code |
393 |
* return next(30) / ((float)(1 << 30));}</pre> |
394 |
* 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 |
* |
399 |
* @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 |
*/ |
403 |
public float nextFloat() { |
404 |
return next(24) / ((float)(1 << 24)); |
405 |
} |
406 |
|
407 |
/** |
408 |
* Returns the next pseudorandom, uniformly distributed |
409 |
* {@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 |
* public double nextDouble() { |
421 |
* 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 |
* randomly chosen bits, then the algorithm shown would choose |
429 |
* {@code double} values from the stated range with perfect uniformity. |
430 |
* <p>[In early versions of Java, the result was incorrectly calculated as: |
431 |
* <pre> {@code |
432 |
* return (((long)next(27) << 27) + next(27)) |
433 |
* / (double)(1L << 54);}</pre> |
434 |
* 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 |
* 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 |
*/ |
446 |
public double nextDouble() { |
447 |
return (((long)(next(26)) << 27) + next(27)) |
448 |
/ (double)(1L << 53); |
449 |
} |
450 |
|
451 |
private double nextNextGaussian; |
452 |
private boolean haveNextNextGaussian = false; |
453 |
|
454 |
/** |
455 |
* Returns the next pseudorandom, Gaussian ("normally") distributed |
456 |
* {@code double} value with mean {@code 0.0} and standard |
457 |
* deviation {@code 1.0} from this random number generator's sequence. |
458 |
* <p> |
459 |
* 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 |
* public double nextGaussian() { |
471 |
* 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 |
* 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 |
* Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>, |
490 |
* section 3.4.1, subsection C, algorithm P. Note that it generates two |
491 |
* independent values at the cost of only one call to {@code StrictMath.log} |
492 |
* and one call to {@code StrictMath.sqrt}. |
493 |
* |
494 |
* @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 |
*/ |
499 |
synchronized public double nextGaussian() { |
500 |
// See Knuth, ACP, Section 3.4.1 Algorithm C. |
501 |
if (haveNextNextGaussian) { |
502 |
haveNextNextGaussian = false; |
503 |
return nextNextGaussian; |
504 |
} else { |
505 |
double v1, v2, s; |
506 |
do { |
507 |
v1 = 2 * nextDouble() - 1; // between -1 and 1 |
508 |
v2 = 2 * nextDouble() - 1; // between -1 and 1 |
509 |
s = v1 * v1 + v2 * v2; |
510 |
} 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 |
} |
516 |
} |
517 |
|
518 |
public IntStream ints() { |
519 |
return Streams.generateInt(this::nextInt); |
520 |
} |
521 |
|
522 |
/** |
523 |
* Serializable fields for Random. |
524 |
* |
525 |
* @serialField seed long |
526 |
* seed for random computations |
527 |
* @serialField nextNextGaussian double |
528 |
* 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 |
}; |
537 |
|
538 |
/** |
539 |
* Reconstitute the {@code Random} instance from a stream (that is, |
540 |
* deserialize it). |
541 |
*/ |
542 |
private void readObject(java.io.ObjectInputStream s) |
543 |
throws java.io.IOException, ClassNotFoundException { |
544 |
|
545 |
ObjectInputStream.GetField fields = s.readFields(); |
546 |
|
547 |
// The seed is read in as {@code long} for |
548 |
// historical reasons, but it is converted to an AtomicLong. |
549 |
long seedVal = fields.get("seed", -1L); |
550 |
if (seedVal < 0) |
551 |
throw new java.io.StreamCorruptedException( |
552 |
"Random: invalid seed"); |
553 |
resetSeed(seedVal); |
554 |
nextNextGaussian = fields.get("nextNextGaussian", 0.0); |
555 |
haveNextNextGaussian = fields.get("haveNextNextGaussian", false); |
556 |
} |
557 |
|
558 |
/** |
559 |
* Save the {@code Random} instance to a stream. |
560 |
*/ |
561 |
synchronized private void writeObject(ObjectOutputStream s) |
562 |
throws IOException { |
563 |
|
564 |
// set the values of the Serializable fields |
565 |
ObjectOutputStream.PutField fields = s.putFields(); |
566 |
|
567 |
// The seed is serialized as a long for historical reasons. |
568 |
fields.put("seed", seed.get()); |
569 |
fields.put("nextNextGaussian", nextNextGaussian); |
570 |
fields.put("haveNextNextGaussian", haveNextNextGaussian); |
571 |
|
572 |
// save them |
573 |
s.writeFields(); |
574 |
} |
575 |
|
576 |
// 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 |
} catch (Exception ex) { throw new Error(ex); } |
584 |
} |
585 |
private void resetSeed(long seedVal) { |
586 |
unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal)); |
587 |
} |
588 |
} |