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