1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.io.ObjectStreamField; |
10 |
import java.security.AccessControlContext; |
11 |
import java.util.Random; |
12 |
import java.util.Spliterator; |
13 |
import java.util.concurrent.atomic.AtomicInteger; |
14 |
import java.util.concurrent.atomic.AtomicLong; |
15 |
import java.util.function.DoubleConsumer; |
16 |
import java.util.function.IntConsumer; |
17 |
import java.util.function.LongConsumer; |
18 |
import java.util.stream.DoubleStream; |
19 |
import java.util.stream.IntStream; |
20 |
import java.util.stream.LongStream; |
21 |
import java.util.stream.StreamSupport; |
22 |
import jdk.internal.misc.Unsafe; |
23 |
import jdk.internal.misc.VM; |
24 |
|
25 |
/** |
26 |
* A random number generator isolated to the current thread. Like the |
27 |
* global {@link java.util.Random} generator used by the {@link |
28 |
* java.lang.Math} class, a {@code ThreadLocalRandom} is initialized |
29 |
* with an internally generated seed that may not otherwise be |
30 |
* modified. When applicable, use of {@code ThreadLocalRandom} rather |
31 |
* than shared {@code Random} objects in concurrent programs will |
32 |
* typically encounter much less overhead and contention. Use of |
33 |
* {@code ThreadLocalRandom} is particularly appropriate when multiple |
34 |
* tasks (for example, each a {@link ForkJoinTask}) use random numbers |
35 |
* in parallel in thread pools. |
36 |
* |
37 |
* <p>Usages of this class should typically be of the form: |
38 |
* {@code ThreadLocalRandom.current().nextX(...)} (where |
39 |
* {@code X} is {@code Int}, {@code Long}, etc). |
40 |
* When all usages are of this form, it is never possible to |
41 |
* accidentally share a {@code ThreadLocalRandom} across multiple threads. |
42 |
* |
43 |
* <p>This class also provides additional commonly used bounded random |
44 |
* generation methods. |
45 |
* |
46 |
* <p>Instances of {@code ThreadLocalRandom} are not cryptographically |
47 |
* secure. Consider instead using {@link java.security.SecureRandom} |
48 |
* in security-sensitive applications. Additionally, |
49 |
* default-constructed instances do not use a cryptographically random |
50 |
* seed unless the {@linkplain System#getProperty system property} |
51 |
* {@systemProperty java.util.secureRandomSeed} is set to {@code true}. |
52 |
* |
53 |
* @since 1.7 |
54 |
* @author Doug Lea |
55 |
*/ |
56 |
public class ThreadLocalRandom extends Random { |
57 |
/* |
58 |
* This class implements the java.util.Random API (and subclasses |
59 |
* Random) using a single static instance that accesses random |
60 |
* number state held in class Thread (primarily, field |
61 |
* threadLocalRandomSeed). In doing so, it also provides a home |
62 |
* for managing package-private utilities that rely on exactly the |
63 |
* same state as needed to maintain the ThreadLocalRandom |
64 |
* instances. We leverage the need for an initialization flag |
65 |
* field to also use it as a "probe" -- a self-adjusting thread |
66 |
* hash used for contention avoidance, as well as a secondary |
67 |
* simpler (xorShift) random seed that is conservatively used to |
68 |
* avoid otherwise surprising users by hijacking the |
69 |
* ThreadLocalRandom sequence. The dual use is a marriage of |
70 |
* convenience, but is a simple and efficient way of reducing |
71 |
* application-level overhead and footprint of most concurrent |
72 |
* programs. Even more opportunistically, we also define here |
73 |
* other package-private utilities that access Thread class |
74 |
* fields. |
75 |
* |
76 |
* Even though this class subclasses java.util.Random, it uses the |
77 |
* same basic algorithm as java.util.SplittableRandom. (See its |
78 |
* internal documentation for explanations, which are not repeated |
79 |
* here.) Because ThreadLocalRandoms are not splittable |
80 |
* though, we use only a single 64bit gamma. |
81 |
* |
82 |
* Because this class is in a different package than class Thread, |
83 |
* field access methods use Unsafe to bypass access control rules. |
84 |
* To conform to the requirements of the Random superclass |
85 |
* constructor, the common static ThreadLocalRandom maintains an |
86 |
* "initialized" field for the sake of rejecting user calls to |
87 |
* setSeed while still allowing a call from constructor. Note |
88 |
* that serialization is completely unnecessary because there is |
89 |
* only a static singleton. But we generate a serial form |
90 |
* containing "rnd" and "initialized" fields to ensure |
91 |
* compatibility across versions. |
92 |
* |
93 |
* Implementations of non-core methods are mostly the same as in |
94 |
* SplittableRandom, that were in part derived from a previous |
95 |
* version of this class. |
96 |
* |
97 |
* The nextLocalGaussian ThreadLocal supports the very rarely used |
98 |
* nextGaussian method by providing a holder for the second of a |
99 |
* pair of them. As is true for the base class version of this |
100 |
* method, this time/space tradeoff is probably never worthwhile, |
101 |
* but we provide identical statistical properties. |
102 |
*/ |
103 |
|
104 |
private static long mix64(long z) { |
105 |
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; |
106 |
z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L; |
107 |
return z ^ (z >>> 33); |
108 |
} |
109 |
|
110 |
private static int mix32(long z) { |
111 |
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; |
112 |
return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32); |
113 |
} |
114 |
|
115 |
/** |
116 |
* Field used only during singleton initialization. |
117 |
* True when constructor completes. |
118 |
*/ |
119 |
boolean initialized; |
120 |
|
121 |
/** Constructor used only for static singleton */ |
122 |
private ThreadLocalRandom() { |
123 |
initialized = true; // false during super() call |
124 |
} |
125 |
|
126 |
/** |
127 |
* Initialize Thread fields for the current thread. Called only |
128 |
* when Thread.threadLocalRandomProbe is zero, indicating that a |
129 |
* thread local seed value needs to be generated. Note that even |
130 |
* though the initialization is purely thread-local, we need to |
131 |
* rely on (static) atomic generators to initialize the values. |
132 |
*/ |
133 |
static final void localInit() { |
134 |
int p = probeGenerator.addAndGet(PROBE_INCREMENT); |
135 |
int probe = (p == 0) ? 1 : p; // skip 0 |
136 |
long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT)); |
137 |
Thread t = Thread.currentThread(); |
138 |
U.putLong(t, SEED, seed); |
139 |
U.putInt(t, PROBE, probe); |
140 |
} |
141 |
|
142 |
/** |
143 |
* Returns the current thread's {@code ThreadLocalRandom}. |
144 |
* |
145 |
* @return the current thread's {@code ThreadLocalRandom} |
146 |
*/ |
147 |
public static ThreadLocalRandom current() { |
148 |
if (U.getInt(Thread.currentThread(), PROBE) == 0) |
149 |
localInit(); |
150 |
return instance; |
151 |
} |
152 |
|
153 |
/** |
154 |
* Throws {@code UnsupportedOperationException}. Setting seeds in |
155 |
* this generator is not supported. |
156 |
* |
157 |
* @throws UnsupportedOperationException always |
158 |
*/ |
159 |
public void setSeed(long seed) { |
160 |
// only allow call from super() constructor |
161 |
if (initialized) |
162 |
throw new UnsupportedOperationException(); |
163 |
} |
164 |
|
165 |
final long nextSeed() { |
166 |
Thread t; long r; // read and update per-thread seed |
167 |
U.putLong(t = Thread.currentThread(), SEED, |
168 |
r = U.getLong(t, SEED) + GAMMA); |
169 |
return r; |
170 |
} |
171 |
|
172 |
/** |
173 |
* Generates a pseudorandom number with the indicated number of |
174 |
* low-order bits. Because this class has no subclasses, this |
175 |
* method cannot be invoked or overridden. |
176 |
* |
177 |
* @param bits random bits |
178 |
* @return the next pseudorandom value from this random number |
179 |
* generator's sequence |
180 |
*/ |
181 |
protected int next(int bits) { |
182 |
return nextInt() >>> (32 - bits); |
183 |
} |
184 |
|
185 |
/** |
186 |
* The form of nextLong used by LongStream Spliterators. If |
187 |
* origin is greater than bound, acts as unbounded form of |
188 |
* nextLong, else as bounded form. |
189 |
* |
190 |
* @param origin the least value, unless greater than bound |
191 |
* @param bound the upper bound (exclusive), must not equal origin |
192 |
* @return a pseudorandom value |
193 |
*/ |
194 |
final long internalNextLong(long origin, long bound) { |
195 |
long r = mix64(nextSeed()); |
196 |
if (origin < bound) { |
197 |
long n = bound - origin, m = n - 1; |
198 |
if ((n & m) == 0L) // power of two |
199 |
r = (r & m) + origin; |
200 |
else if (n > 0L) { // reject over-represented candidates |
201 |
for (long u = r >>> 1; // ensure nonnegative |
202 |
u + m - (r = u % n) < 0L; // rejection check |
203 |
u = mix64(nextSeed()) >>> 1) // retry |
204 |
; |
205 |
r += origin; |
206 |
} |
207 |
else { // range not representable as long |
208 |
while (r < origin || r >= bound) |
209 |
r = mix64(nextSeed()); |
210 |
} |
211 |
} |
212 |
return r; |
213 |
} |
214 |
|
215 |
/** |
216 |
* The form of nextInt used by IntStream Spliterators. |
217 |
* Exactly the same as long version, except for types. |
218 |
* |
219 |
* @param origin the least value, unless greater than bound |
220 |
* @param bound the upper bound (exclusive), must not equal origin |
221 |
* @return a pseudorandom value |
222 |
*/ |
223 |
final int internalNextInt(int origin, int bound) { |
224 |
int r = mix32(nextSeed()); |
225 |
if (origin < bound) { |
226 |
int n = bound - origin, m = n - 1; |
227 |
if ((n & m) == 0) |
228 |
r = (r & m) + origin; |
229 |
else if (n > 0) { |
230 |
for (int u = r >>> 1; |
231 |
u + m - (r = u % n) < 0; |
232 |
u = mix32(nextSeed()) >>> 1) |
233 |
; |
234 |
r += origin; |
235 |
} |
236 |
else { |
237 |
while (r < origin || r >= bound) |
238 |
r = mix32(nextSeed()); |
239 |
} |
240 |
} |
241 |
return r; |
242 |
} |
243 |
|
244 |
/** |
245 |
* The form of nextDouble used by DoubleStream Spliterators. |
246 |
* |
247 |
* @param origin the least value, unless greater than bound |
248 |
* @param bound the upper bound (exclusive), must not equal origin |
249 |
* @return a pseudorandom value |
250 |
*/ |
251 |
final double internalNextDouble(double origin, double bound) { |
252 |
double r = (nextLong() >>> 11) * DOUBLE_UNIT; |
253 |
if (origin < bound) { |
254 |
r = r * (bound - origin) + origin; |
255 |
if (r >= bound) // correct for rounding |
256 |
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); |
257 |
} |
258 |
return r; |
259 |
} |
260 |
|
261 |
/** |
262 |
* Returns a pseudorandom {@code int} value. |
263 |
* |
264 |
* @return a pseudorandom {@code int} value |
265 |
*/ |
266 |
public int nextInt() { |
267 |
return mix32(nextSeed()); |
268 |
} |
269 |
|
270 |
/** |
271 |
* Returns a pseudorandom {@code int} value between zero (inclusive) |
272 |
* and the specified bound (exclusive). |
273 |
* |
274 |
* @param bound the upper bound (exclusive). Must be positive. |
275 |
* @return a pseudorandom {@code int} value between zero |
276 |
* (inclusive) and the bound (exclusive) |
277 |
* @throws IllegalArgumentException if {@code bound} is not positive |
278 |
*/ |
279 |
public int nextInt(int bound) { |
280 |
if (bound <= 0) |
281 |
throw new IllegalArgumentException(BAD_BOUND); |
282 |
int r = mix32(nextSeed()); |
283 |
int m = bound - 1; |
284 |
if ((bound & m) == 0) // power of two |
285 |
r &= m; |
286 |
else { // reject over-represented candidates |
287 |
for (int u = r >>> 1; |
288 |
u + m - (r = u % bound) < 0; |
289 |
u = mix32(nextSeed()) >>> 1) |
290 |
; |
291 |
} |
292 |
return r; |
293 |
} |
294 |
|
295 |
/** |
296 |
* Returns a pseudorandom {@code int} value between the specified |
297 |
* origin (inclusive) and the specified bound (exclusive). |
298 |
* |
299 |
* @param origin the least value returned |
300 |
* @param bound the upper bound (exclusive) |
301 |
* @return a pseudorandom {@code int} value between the origin |
302 |
* (inclusive) and the bound (exclusive) |
303 |
* @throws IllegalArgumentException if {@code origin} is greater than |
304 |
* or equal to {@code bound} |
305 |
*/ |
306 |
public int nextInt(int origin, int bound) { |
307 |
if (origin >= bound) |
308 |
throw new IllegalArgumentException(BAD_RANGE); |
309 |
return internalNextInt(origin, bound); |
310 |
} |
311 |
|
312 |
/** |
313 |
* Returns a pseudorandom {@code long} value. |
314 |
* |
315 |
* @return a pseudorandom {@code long} value |
316 |
*/ |
317 |
public long nextLong() { |
318 |
return mix64(nextSeed()); |
319 |
} |
320 |
|
321 |
/** |
322 |
* Returns a pseudorandom {@code long} value between zero (inclusive) |
323 |
* and the specified bound (exclusive). |
324 |
* |
325 |
* @param bound the upper bound (exclusive). Must be positive. |
326 |
* @return a pseudorandom {@code long} value between zero |
327 |
* (inclusive) and the bound (exclusive) |
328 |
* @throws IllegalArgumentException if {@code bound} is not positive |
329 |
*/ |
330 |
public long nextLong(long bound) { |
331 |
if (bound <= 0) |
332 |
throw new IllegalArgumentException(BAD_BOUND); |
333 |
long r = mix64(nextSeed()); |
334 |
long m = bound - 1; |
335 |
if ((bound & m) == 0L) // power of two |
336 |
r &= m; |
337 |
else { // reject over-represented candidates |
338 |
for (long u = r >>> 1; |
339 |
u + m - (r = u % bound) < 0L; |
340 |
u = mix64(nextSeed()) >>> 1) |
341 |
; |
342 |
} |
343 |
return r; |
344 |
} |
345 |
|
346 |
/** |
347 |
* Returns a pseudorandom {@code long} value between the specified |
348 |
* origin (inclusive) and the specified bound (exclusive). |
349 |
* |
350 |
* @param origin the least value returned |
351 |
* @param bound the upper bound (exclusive) |
352 |
* @return a pseudorandom {@code long} value between the origin |
353 |
* (inclusive) and the bound (exclusive) |
354 |
* @throws IllegalArgumentException if {@code origin} is greater than |
355 |
* or equal to {@code bound} |
356 |
*/ |
357 |
public long nextLong(long origin, long bound) { |
358 |
if (origin >= bound) |
359 |
throw new IllegalArgumentException(BAD_RANGE); |
360 |
return internalNextLong(origin, bound); |
361 |
} |
362 |
|
363 |
/** |
364 |
* Returns a pseudorandom {@code double} value between zero |
365 |
* (inclusive) and one (exclusive). |
366 |
* |
367 |
* @return a pseudorandom {@code double} value between zero |
368 |
* (inclusive) and one (exclusive) |
369 |
*/ |
370 |
public double nextDouble() { |
371 |
return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT; |
372 |
} |
373 |
|
374 |
/** |
375 |
* Returns a pseudorandom {@code double} value between 0.0 |
376 |
* (inclusive) and the specified bound (exclusive). |
377 |
* |
378 |
* @param bound the upper bound (exclusive). Must be positive. |
379 |
* @return a pseudorandom {@code double} value between zero |
380 |
* (inclusive) and the bound (exclusive) |
381 |
* @throws IllegalArgumentException if {@code bound} is not positive |
382 |
*/ |
383 |
public double nextDouble(double bound) { |
384 |
if (!(bound > 0.0)) |
385 |
throw new IllegalArgumentException(BAD_BOUND); |
386 |
double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound; |
387 |
return (result < bound) ? result : // correct for rounding |
388 |
Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); |
389 |
} |
390 |
|
391 |
/** |
392 |
* Returns a pseudorandom {@code double} value between the specified |
393 |
* origin (inclusive) and bound (exclusive). |
394 |
* |
395 |
* @param origin the least value returned |
396 |
* @param bound the upper bound (exclusive) |
397 |
* @return a pseudorandom {@code double} value between the origin |
398 |
* (inclusive) and the bound (exclusive) |
399 |
* @throws IllegalArgumentException if {@code origin} is greater than |
400 |
* or equal to {@code bound} |
401 |
*/ |
402 |
public double nextDouble(double origin, double bound) { |
403 |
if (!(origin < bound)) |
404 |
throw new IllegalArgumentException(BAD_RANGE); |
405 |
return internalNextDouble(origin, bound); |
406 |
} |
407 |
|
408 |
/** |
409 |
* Returns a pseudorandom {@code boolean} value. |
410 |
* |
411 |
* @return a pseudorandom {@code boolean} value |
412 |
*/ |
413 |
public boolean nextBoolean() { |
414 |
return mix32(nextSeed()) < 0; |
415 |
} |
416 |
|
417 |
/** |
418 |
* Returns a pseudorandom {@code float} value between zero |
419 |
* (inclusive) and one (exclusive). |
420 |
* |
421 |
* @return a pseudorandom {@code float} value between zero |
422 |
* (inclusive) and one (exclusive) |
423 |
*/ |
424 |
public float nextFloat() { |
425 |
return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT; |
426 |
} |
427 |
|
428 |
public double nextGaussian() { |
429 |
// Use nextLocalGaussian instead of nextGaussian field |
430 |
Double d = nextLocalGaussian.get(); |
431 |
if (d != null) { |
432 |
nextLocalGaussian.set(null); |
433 |
return d.doubleValue(); |
434 |
} |
435 |
double v1, v2, s; |
436 |
do { |
437 |
v1 = 2 * nextDouble() - 1; // between -1 and 1 |
438 |
v2 = 2 * nextDouble() - 1; // between -1 and 1 |
439 |
s = v1 * v1 + v2 * v2; |
440 |
} while (s >= 1 || s == 0); |
441 |
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
442 |
nextLocalGaussian.set(Double.valueOf(v2 * multiplier)); |
443 |
return v1 * multiplier; |
444 |
} |
445 |
|
446 |
// stream methods, coded in a way intended to better isolate for |
447 |
// maintenance purposes the small differences across forms. |
448 |
|
449 |
/** |
450 |
* Returns a stream producing the given {@code streamSize} number of |
451 |
* pseudorandom {@code int} values. |
452 |
* |
453 |
* @param streamSize the number of values to generate |
454 |
* @return a stream of pseudorandom {@code int} values |
455 |
* @throws IllegalArgumentException if {@code streamSize} is |
456 |
* less than zero |
457 |
* @since 1.8 |
458 |
*/ |
459 |
public IntStream ints(long streamSize) { |
460 |
if (streamSize < 0L) |
461 |
throw new IllegalArgumentException(BAD_SIZE); |
462 |
return StreamSupport.intStream |
463 |
(new RandomIntsSpliterator |
464 |
(0L, streamSize, Integer.MAX_VALUE, 0), |
465 |
false); |
466 |
} |
467 |
|
468 |
/** |
469 |
* Returns an effectively unlimited stream of pseudorandom {@code int} |
470 |
* values. |
471 |
* |
472 |
* @implNote This method is implemented to be equivalent to {@code |
473 |
* ints(Long.MAX_VALUE)}. |
474 |
* |
475 |
* @return a stream of pseudorandom {@code int} values |
476 |
* @since 1.8 |
477 |
*/ |
478 |
public IntStream ints() { |
479 |
return StreamSupport.intStream |
480 |
(new RandomIntsSpliterator |
481 |
(0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), |
482 |
false); |
483 |
} |
484 |
|
485 |
/** |
486 |
* Returns a stream producing the given {@code streamSize} number |
487 |
* of pseudorandom {@code int} values, each conforming to the given |
488 |
* origin (inclusive) and bound (exclusive). |
489 |
* |
490 |
* @param streamSize the number of values to generate |
491 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
492 |
* @param randomNumberBound the bound (exclusive) of each random value |
493 |
* @return a stream of pseudorandom {@code int} values, |
494 |
* each with the given origin (inclusive) and bound (exclusive) |
495 |
* @throws IllegalArgumentException if {@code streamSize} is |
496 |
* less than zero, or {@code randomNumberOrigin} |
497 |
* is greater than or equal to {@code randomNumberBound} |
498 |
* @since 1.8 |
499 |
*/ |
500 |
public IntStream ints(long streamSize, int randomNumberOrigin, |
501 |
int randomNumberBound) { |
502 |
if (streamSize < 0L) |
503 |
throw new IllegalArgumentException(BAD_SIZE); |
504 |
if (randomNumberOrigin >= randomNumberBound) |
505 |
throw new IllegalArgumentException(BAD_RANGE); |
506 |
return StreamSupport.intStream |
507 |
(new RandomIntsSpliterator |
508 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
509 |
false); |
510 |
} |
511 |
|
512 |
/** |
513 |
* Returns an effectively unlimited stream of pseudorandom {@code |
514 |
* int} values, each conforming to the given origin (inclusive) and bound |
515 |
* (exclusive). |
516 |
* |
517 |
* @implNote This method is implemented to be equivalent to {@code |
518 |
* ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
519 |
* |
520 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
521 |
* @param randomNumberBound the bound (exclusive) of each random value |
522 |
* @return a stream of pseudorandom {@code int} values, |
523 |
* each with the given origin (inclusive) and bound (exclusive) |
524 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
525 |
* is greater than or equal to {@code randomNumberBound} |
526 |
* @since 1.8 |
527 |
*/ |
528 |
public IntStream ints(int randomNumberOrigin, int randomNumberBound) { |
529 |
if (randomNumberOrigin >= randomNumberBound) |
530 |
throw new IllegalArgumentException(BAD_RANGE); |
531 |
return StreamSupport.intStream |
532 |
(new RandomIntsSpliterator |
533 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
534 |
false); |
535 |
} |
536 |
|
537 |
/** |
538 |
* Returns a stream producing the given {@code streamSize} number of |
539 |
* pseudorandom {@code long} values. |
540 |
* |
541 |
* @param streamSize the number of values to generate |
542 |
* @return a stream of pseudorandom {@code long} values |
543 |
* @throws IllegalArgumentException if {@code streamSize} is |
544 |
* less than zero |
545 |
* @since 1.8 |
546 |
*/ |
547 |
public LongStream longs(long streamSize) { |
548 |
if (streamSize < 0L) |
549 |
throw new IllegalArgumentException(BAD_SIZE); |
550 |
return StreamSupport.longStream |
551 |
(new RandomLongsSpliterator |
552 |
(0L, streamSize, Long.MAX_VALUE, 0L), |
553 |
false); |
554 |
} |
555 |
|
556 |
/** |
557 |
* Returns an effectively unlimited stream of pseudorandom {@code long} |
558 |
* values. |
559 |
* |
560 |
* @implNote This method is implemented to be equivalent to {@code |
561 |
* longs(Long.MAX_VALUE)}. |
562 |
* |
563 |
* @return a stream of pseudorandom {@code long} values |
564 |
* @since 1.8 |
565 |
*/ |
566 |
public LongStream longs() { |
567 |
return StreamSupport.longStream |
568 |
(new RandomLongsSpliterator |
569 |
(0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), |
570 |
false); |
571 |
} |
572 |
|
573 |
/** |
574 |
* Returns a stream producing the given {@code streamSize} number of |
575 |
* pseudorandom {@code long}, each conforming to the given origin |
576 |
* (inclusive) and bound (exclusive). |
577 |
* |
578 |
* @param streamSize the number of values to generate |
579 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
580 |
* @param randomNumberBound the bound (exclusive) of each random value |
581 |
* @return a stream of pseudorandom {@code long} values, |
582 |
* each with the given origin (inclusive) and bound (exclusive) |
583 |
* @throws IllegalArgumentException if {@code streamSize} is |
584 |
* less than zero, or {@code randomNumberOrigin} |
585 |
* is greater than or equal to {@code randomNumberBound} |
586 |
* @since 1.8 |
587 |
*/ |
588 |
public LongStream longs(long streamSize, long randomNumberOrigin, |
589 |
long randomNumberBound) { |
590 |
if (streamSize < 0L) |
591 |
throw new IllegalArgumentException(BAD_SIZE); |
592 |
if (randomNumberOrigin >= randomNumberBound) |
593 |
throw new IllegalArgumentException(BAD_RANGE); |
594 |
return StreamSupport.longStream |
595 |
(new RandomLongsSpliterator |
596 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
597 |
false); |
598 |
} |
599 |
|
600 |
/** |
601 |
* Returns an effectively unlimited stream of pseudorandom {@code |
602 |
* long} values, each conforming to the given origin (inclusive) and bound |
603 |
* (exclusive). |
604 |
* |
605 |
* @implNote This method is implemented to be equivalent to {@code |
606 |
* longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
607 |
* |
608 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
609 |
* @param randomNumberBound the bound (exclusive) of each random value |
610 |
* @return a stream of pseudorandom {@code long} values, |
611 |
* each with the given origin (inclusive) and bound (exclusive) |
612 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
613 |
* is greater than or equal to {@code randomNumberBound} |
614 |
* @since 1.8 |
615 |
*/ |
616 |
public LongStream longs(long randomNumberOrigin, long randomNumberBound) { |
617 |
if (randomNumberOrigin >= randomNumberBound) |
618 |
throw new IllegalArgumentException(BAD_RANGE); |
619 |
return StreamSupport.longStream |
620 |
(new RandomLongsSpliterator |
621 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
622 |
false); |
623 |
} |
624 |
|
625 |
/** |
626 |
* Returns a stream producing the given {@code streamSize} number of |
627 |
* pseudorandom {@code double} values, each between zero |
628 |
* (inclusive) and one (exclusive). |
629 |
* |
630 |
* @param streamSize the number of values to generate |
631 |
* @return a stream of {@code double} values |
632 |
* @throws IllegalArgumentException if {@code streamSize} is |
633 |
* less than zero |
634 |
* @since 1.8 |
635 |
*/ |
636 |
public DoubleStream doubles(long streamSize) { |
637 |
if (streamSize < 0L) |
638 |
throw new IllegalArgumentException(BAD_SIZE); |
639 |
return StreamSupport.doubleStream |
640 |
(new RandomDoublesSpliterator |
641 |
(0L, streamSize, Double.MAX_VALUE, 0.0), |
642 |
false); |
643 |
} |
644 |
|
645 |
/** |
646 |
* Returns an effectively unlimited stream of pseudorandom {@code |
647 |
* double} values, each between zero (inclusive) and one |
648 |
* (exclusive). |
649 |
* |
650 |
* @implNote This method is implemented to be equivalent to {@code |
651 |
* doubles(Long.MAX_VALUE)}. |
652 |
* |
653 |
* @return a stream of pseudorandom {@code double} values |
654 |
* @since 1.8 |
655 |
*/ |
656 |
public DoubleStream doubles() { |
657 |
return StreamSupport.doubleStream |
658 |
(new RandomDoublesSpliterator |
659 |
(0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), |
660 |
false); |
661 |
} |
662 |
|
663 |
/** |
664 |
* Returns a stream producing the given {@code streamSize} number of |
665 |
* pseudorandom {@code double} values, each conforming to the given origin |
666 |
* (inclusive) and bound (exclusive). |
667 |
* |
668 |
* @param streamSize the number of values to generate |
669 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
670 |
* @param randomNumberBound the bound (exclusive) of each random value |
671 |
* @return a stream of pseudorandom {@code double} values, |
672 |
* each with the given origin (inclusive) and bound (exclusive) |
673 |
* @throws IllegalArgumentException if {@code streamSize} is |
674 |
* less than zero, or {@code randomNumberOrigin} |
675 |
* is greater than or equal to {@code randomNumberBound} |
676 |
* @since 1.8 |
677 |
*/ |
678 |
public DoubleStream doubles(long streamSize, double randomNumberOrigin, |
679 |
double randomNumberBound) { |
680 |
if (streamSize < 0L) |
681 |
throw new IllegalArgumentException(BAD_SIZE); |
682 |
if (!(randomNumberOrigin < randomNumberBound)) |
683 |
throw new IllegalArgumentException(BAD_RANGE); |
684 |
return StreamSupport.doubleStream |
685 |
(new RandomDoublesSpliterator |
686 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
687 |
false); |
688 |
} |
689 |
|
690 |
/** |
691 |
* Returns an effectively unlimited stream of pseudorandom {@code |
692 |
* double} values, each conforming to the given origin (inclusive) and bound |
693 |
* (exclusive). |
694 |
* |
695 |
* @implNote This method is implemented to be equivalent to {@code |
696 |
* doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
697 |
* |
698 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
699 |
* @param randomNumberBound the bound (exclusive) of each random value |
700 |
* @return a stream of pseudorandom {@code double} values, |
701 |
* each with the given origin (inclusive) and bound (exclusive) |
702 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
703 |
* is greater than or equal to {@code randomNumberBound} |
704 |
* @since 1.8 |
705 |
*/ |
706 |
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { |
707 |
if (!(randomNumberOrigin < randomNumberBound)) |
708 |
throw new IllegalArgumentException(BAD_RANGE); |
709 |
return StreamSupport.doubleStream |
710 |
(new RandomDoublesSpliterator |
711 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
712 |
false); |
713 |
} |
714 |
|
715 |
/** |
716 |
* Spliterator for int streams. We multiplex the four int |
717 |
* versions into one class by treating a bound less than origin as |
718 |
* unbounded, and also by treating "infinite" as equivalent to |
719 |
* Long.MAX_VALUE. For splits, it uses the standard divide-by-two |
720 |
* approach. The long and double versions of this class are |
721 |
* identical except for types. |
722 |
*/ |
723 |
private static final class RandomIntsSpliterator |
724 |
implements Spliterator.OfInt { |
725 |
long index; |
726 |
final long fence; |
727 |
final int origin; |
728 |
final int bound; |
729 |
RandomIntsSpliterator(long index, long fence, |
730 |
int origin, int bound) { |
731 |
this.index = index; this.fence = fence; |
732 |
this.origin = origin; this.bound = bound; |
733 |
} |
734 |
|
735 |
public RandomIntsSpliterator trySplit() { |
736 |
long i = index, m = (i + fence) >>> 1; |
737 |
return (m <= i) ? null : |
738 |
new RandomIntsSpliterator(i, index = m, origin, bound); |
739 |
} |
740 |
|
741 |
public long estimateSize() { |
742 |
return fence - index; |
743 |
} |
744 |
|
745 |
public int characteristics() { |
746 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
747 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
748 |
} |
749 |
|
750 |
public boolean tryAdvance(IntConsumer consumer) { |
751 |
if (consumer == null) throw new NullPointerException(); |
752 |
long i = index, f = fence; |
753 |
if (i < f) { |
754 |
consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound)); |
755 |
index = i + 1; |
756 |
return true; |
757 |
} |
758 |
return false; |
759 |
} |
760 |
|
761 |
public void forEachRemaining(IntConsumer consumer) { |
762 |
if (consumer == null) throw new NullPointerException(); |
763 |
long i = index, f = fence; |
764 |
if (i < f) { |
765 |
index = f; |
766 |
int o = origin, b = bound; |
767 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
768 |
do { |
769 |
consumer.accept(rng.internalNextInt(o, b)); |
770 |
} while (++i < f); |
771 |
} |
772 |
} |
773 |
} |
774 |
|
775 |
/** |
776 |
* Spliterator for long streams. |
777 |
*/ |
778 |
private static final class RandomLongsSpliterator |
779 |
implements Spliterator.OfLong { |
780 |
long index; |
781 |
final long fence; |
782 |
final long origin; |
783 |
final long bound; |
784 |
RandomLongsSpliterator(long index, long fence, |
785 |
long origin, long bound) { |
786 |
this.index = index; this.fence = fence; |
787 |
this.origin = origin; this.bound = bound; |
788 |
} |
789 |
|
790 |
public RandomLongsSpliterator trySplit() { |
791 |
long i = index, m = (i + fence) >>> 1; |
792 |
return (m <= i) ? null : |
793 |
new RandomLongsSpliterator(i, index = m, origin, bound); |
794 |
} |
795 |
|
796 |
public long estimateSize() { |
797 |
return fence - index; |
798 |
} |
799 |
|
800 |
public int characteristics() { |
801 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
802 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
803 |
} |
804 |
|
805 |
public boolean tryAdvance(LongConsumer consumer) { |
806 |
if (consumer == null) throw new NullPointerException(); |
807 |
long i = index, f = fence; |
808 |
if (i < f) { |
809 |
consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound)); |
810 |
index = i + 1; |
811 |
return true; |
812 |
} |
813 |
return false; |
814 |
} |
815 |
|
816 |
public void forEachRemaining(LongConsumer consumer) { |
817 |
if (consumer == null) throw new NullPointerException(); |
818 |
long i = index, f = fence; |
819 |
if (i < f) { |
820 |
index = f; |
821 |
long o = origin, b = bound; |
822 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
823 |
do { |
824 |
consumer.accept(rng.internalNextLong(o, b)); |
825 |
} while (++i < f); |
826 |
} |
827 |
} |
828 |
|
829 |
} |
830 |
|
831 |
/** |
832 |
* Spliterator for double streams. |
833 |
*/ |
834 |
private static final class RandomDoublesSpliterator |
835 |
implements Spliterator.OfDouble { |
836 |
long index; |
837 |
final long fence; |
838 |
final double origin; |
839 |
final double bound; |
840 |
RandomDoublesSpliterator(long index, long fence, |
841 |
double origin, double bound) { |
842 |
this.index = index; this.fence = fence; |
843 |
this.origin = origin; this.bound = bound; |
844 |
} |
845 |
|
846 |
public RandomDoublesSpliterator trySplit() { |
847 |
long i = index, m = (i + fence) >>> 1; |
848 |
return (m <= i) ? null : |
849 |
new RandomDoublesSpliterator(i, index = m, origin, bound); |
850 |
} |
851 |
|
852 |
public long estimateSize() { |
853 |
return fence - index; |
854 |
} |
855 |
|
856 |
public int characteristics() { |
857 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
858 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
859 |
} |
860 |
|
861 |
public boolean tryAdvance(DoubleConsumer consumer) { |
862 |
if (consumer == null) throw new NullPointerException(); |
863 |
long i = index, f = fence; |
864 |
if (i < f) { |
865 |
consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound)); |
866 |
index = i + 1; |
867 |
return true; |
868 |
} |
869 |
return false; |
870 |
} |
871 |
|
872 |
public void forEachRemaining(DoubleConsumer consumer) { |
873 |
if (consumer == null) throw new NullPointerException(); |
874 |
long i = index, f = fence; |
875 |
if (i < f) { |
876 |
index = f; |
877 |
double o = origin, b = bound; |
878 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
879 |
do { |
880 |
consumer.accept(rng.internalNextDouble(o, b)); |
881 |
} while (++i < f); |
882 |
} |
883 |
} |
884 |
} |
885 |
|
886 |
|
887 |
// Within-package utilities |
888 |
|
889 |
/* |
890 |
* Descriptions of the usages of the methods below can be found in |
891 |
* the classes that use them. Briefly, a thread's "probe" value is |
892 |
* a non-zero hash code that (probably) does not collide with |
893 |
* other existing threads with respect to any power of two |
894 |
* collision space. When it does collide, it is pseudo-randomly |
895 |
* adjusted (using a Marsaglia XorShift). The nextSecondarySeed |
896 |
* method is used in the same contexts as ThreadLocalRandom, but |
897 |
* only for transient usages such as random adaptive spin/block |
898 |
* sequences for which a cheap RNG suffices and for which it could |
899 |
* in principle disrupt user-visible statistical properties of the |
900 |
* main ThreadLocalRandom if we were to use it. |
901 |
* |
902 |
* Note: Because of package-protection issues, versions of some |
903 |
* these methods also appear in some subpackage classes. |
904 |
*/ |
905 |
|
906 |
/** |
907 |
* Returns the probe value for the current thread without forcing |
908 |
* initialization. Note that invoking ThreadLocalRandom.current() |
909 |
* can be used to force initialization on zero return. |
910 |
*/ |
911 |
static final int getProbe() { |
912 |
return U.getInt(Thread.currentThread(), PROBE); |
913 |
} |
914 |
|
915 |
/** |
916 |
* Pseudo-randomly advances and records the given probe value for the |
917 |
* given thread. |
918 |
*/ |
919 |
static final int advanceProbe(int probe) { |
920 |
probe ^= probe << 13; // xorshift |
921 |
probe ^= probe >>> 17; |
922 |
probe ^= probe << 5; |
923 |
U.putInt(Thread.currentThread(), PROBE, probe); |
924 |
return probe; |
925 |
} |
926 |
|
927 |
/** |
928 |
* Returns the pseudo-randomly initialized or updated secondary seed. |
929 |
*/ |
930 |
static final int nextSecondarySeed() { |
931 |
int r; |
932 |
Thread t = Thread.currentThread(); |
933 |
if ((r = U.getInt(t, SECONDARY)) != 0) { |
934 |
r ^= r << 13; // xorshift |
935 |
r ^= r >>> 17; |
936 |
r ^= r << 5; |
937 |
} |
938 |
else if ((r = mix32(seeder.getAndAdd(SEEDER_INCREMENT))) == 0) |
939 |
r = 1; // avoid zero |
940 |
U.putInt(t, SECONDARY, r); |
941 |
return r; |
942 |
} |
943 |
|
944 |
// Support for other package-private ThreadLocal access |
945 |
|
946 |
/** |
947 |
* Erases ThreadLocals by nulling out Thread maps. |
948 |
*/ |
949 |
static final void eraseThreadLocals(Thread thread) { |
950 |
U.putObject(thread, THREADLOCALS, null); |
951 |
U.putObject(thread, INHERITABLETHREADLOCALS, null); |
952 |
} |
953 |
|
954 |
static final void setInheritedAccessControlContext(Thread thread, |
955 |
AccessControlContext acc) { |
956 |
U.putObjectRelease(thread, INHERITEDACCESSCONTROLCONTEXT, acc); |
957 |
} |
958 |
|
959 |
// Serialization support |
960 |
|
961 |
private static final long serialVersionUID = -5851777807851030925L; |
962 |
|
963 |
/** |
964 |
* @serialField rnd long |
965 |
* seed for random computations |
966 |
* @serialField initialized boolean |
967 |
* always true |
968 |
*/ |
969 |
private static final ObjectStreamField[] serialPersistentFields = { |
970 |
new ObjectStreamField("rnd", long.class), |
971 |
new ObjectStreamField("initialized", boolean.class), |
972 |
}; |
973 |
|
974 |
/** |
975 |
* Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it). |
976 |
* @param s the stream |
977 |
* @throws java.io.IOException if an I/O error occurs |
978 |
*/ |
979 |
private void writeObject(java.io.ObjectOutputStream s) |
980 |
throws java.io.IOException { |
981 |
|
982 |
java.io.ObjectOutputStream.PutField fields = s.putFields(); |
983 |
fields.put("rnd", U.getLong(Thread.currentThread(), SEED)); |
984 |
fields.put("initialized", true); |
985 |
s.writeFields(); |
986 |
} |
987 |
|
988 |
/** |
989 |
* Returns the {@link #current() current} thread's {@code ThreadLocalRandom}. |
990 |
* @return the {@link #current() current} thread's {@code ThreadLocalRandom} |
991 |
*/ |
992 |
private Object readResolve() { |
993 |
return current(); |
994 |
} |
995 |
|
996 |
// Static initialization |
997 |
|
998 |
/** |
999 |
* The seed increment. |
1000 |
*/ |
1001 |
private static final long GAMMA = 0x9e3779b97f4a7c15L; |
1002 |
|
1003 |
/** |
1004 |
* The increment for generating probe values. |
1005 |
*/ |
1006 |
private static final int PROBE_INCREMENT = 0x9e3779b9; |
1007 |
|
1008 |
/** |
1009 |
* The increment of seeder per new instance. |
1010 |
*/ |
1011 |
private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL; |
1012 |
|
1013 |
/** |
1014 |
* The least non-zero value returned by nextDouble(). This value |
1015 |
* is scaled by a random value of 53 bits to produce a result. |
1016 |
*/ |
1017 |
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) |
1018 |
private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24) |
1019 |
|
1020 |
// IllegalArgumentException messages |
1021 |
static final String BAD_BOUND = "bound must be positive"; |
1022 |
static final String BAD_RANGE = "bound must be greater than origin"; |
1023 |
static final String BAD_SIZE = "size must be non-negative"; |
1024 |
|
1025 |
// Unsafe mechanics |
1026 |
private static final Unsafe U = Unsafe.getUnsafe(); |
1027 |
private static final long SEED; |
1028 |
private static final long PROBE; |
1029 |
private static final long SECONDARY; |
1030 |
private static final long THREADLOCALS; |
1031 |
private static final long INHERITABLETHREADLOCALS; |
1032 |
private static final long INHERITEDACCESSCONTROLCONTEXT; |
1033 |
static { |
1034 |
try { |
1035 |
SEED = U.objectFieldOffset |
1036 |
(Thread.class.getDeclaredField("threadLocalRandomSeed")); |
1037 |
PROBE = U.objectFieldOffset |
1038 |
(Thread.class.getDeclaredField("threadLocalRandomProbe")); |
1039 |
SECONDARY = U.objectFieldOffset |
1040 |
(Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); |
1041 |
THREADLOCALS = U.objectFieldOffset |
1042 |
(Thread.class.getDeclaredField("threadLocals")); |
1043 |
INHERITABLETHREADLOCALS = U.objectFieldOffset |
1044 |
(Thread.class.getDeclaredField("inheritableThreadLocals")); |
1045 |
INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset |
1046 |
(Thread.class.getDeclaredField("inheritedAccessControlContext")); |
1047 |
} catch (ReflectiveOperationException e) { |
1048 |
throw new ExceptionInInitializerError(e); |
1049 |
} |
1050 |
} |
1051 |
|
1052 |
/** Rarely-used holder for the second of a pair of Gaussians */ |
1053 |
private static final ThreadLocal<Double> nextLocalGaussian = |
1054 |
new ThreadLocal<>(); |
1055 |
|
1056 |
/** Generates per-thread initialization/probe field */ |
1057 |
private static final AtomicInteger probeGenerator = new AtomicInteger(); |
1058 |
|
1059 |
/** The common ThreadLocalRandom */ |
1060 |
static final ThreadLocalRandom instance = new ThreadLocalRandom(); |
1061 |
|
1062 |
/** |
1063 |
* The next seed for default constructors. |
1064 |
*/ |
1065 |
private static final AtomicLong seeder |
1066 |
= new AtomicLong(mix64(System.currentTimeMillis()) ^ |
1067 |
mix64(System.nanoTime())); |
1068 |
|
1069 |
// at end of <clinit> to survive static initialization circularity |
1070 |
static { |
1071 |
String sec = VM.getSavedProperty("java.util.secureRandomSeed"); |
1072 |
if (Boolean.parseBoolean(sec)) { |
1073 |
byte[] seedBytes = java.security.SecureRandom.getSeed(8); |
1074 |
long s = (long)seedBytes[0] & 0xffL; |
1075 |
for (int i = 1; i < 8; ++i) |
1076 |
s = (s << 8) | ((long)seedBytes[i] & 0xffL); |
1077 |
seeder.set(s); |
1078 |
} |
1079 |
} |
1080 |
} |