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 |
/** |
172 |
* Generates a pseudorandom number with the indicated number of |
173 |
* low-order bits. Because this class has no subclasses, this |
174 |
* method cannot be invoked or overridden. |
175 |
* |
176 |
* @param bits random bits |
177 |
* @return the next pseudorandom value from this random number |
178 |
* generator's sequence |
179 |
*/ |
180 |
protected int next(int bits) { |
181 |
return nextInt() >>> (32 - bits); |
182 |
} |
183 |
|
184 |
/** |
185 |
* The form of nextLong used by LongStream Spliterators. If |
186 |
* origin is greater than bound, acts as unbounded form of |
187 |
* nextLong, else as bounded form. |
188 |
* |
189 |
* @param origin the least value, unless greater than bound |
190 |
* @param bound the upper bound (exclusive), must not equal origin |
191 |
* @return a pseudorandom value |
192 |
*/ |
193 |
final long internalNextLong(long origin, long bound) { |
194 |
long r = mix64(nextSeed()); |
195 |
if (origin < bound) { |
196 |
long n = bound - origin, m = n - 1; |
197 |
if ((n & m) == 0L) // power of two |
198 |
r = (r & m) + origin; |
199 |
else if (n > 0L) { // reject over-represented candidates |
200 |
for (long u = r >>> 1; // ensure nonnegative |
201 |
u + m - (r = u % n) < 0L; // rejection check |
202 |
u = mix64(nextSeed()) >>> 1) // retry |
203 |
; |
204 |
r += origin; |
205 |
} |
206 |
else { // range not representable as long |
207 |
while (r < origin || r >= bound) |
208 |
r = mix64(nextSeed()); |
209 |
} |
210 |
} |
211 |
return r; |
212 |
} |
213 |
|
214 |
/** |
215 |
* The form of nextInt used by IntStream Spliterators. |
216 |
* Exactly the same as long version, except for types. |
217 |
* |
218 |
* @param origin the least value, unless greater than bound |
219 |
* @param bound the upper bound (exclusive), must not equal origin |
220 |
* @return a pseudorandom value |
221 |
*/ |
222 |
final int internalNextInt(int origin, int bound) { |
223 |
int r = mix32(nextSeed()); |
224 |
if (origin < bound) { |
225 |
int n = bound - origin, m = n - 1; |
226 |
if ((n & m) == 0) |
227 |
r = (r & m) + origin; |
228 |
else if (n > 0) { |
229 |
for (int u = r >>> 1; |
230 |
u + m - (r = u % n) < 0; |
231 |
u = mix32(nextSeed()) >>> 1) |
232 |
; |
233 |
r += origin; |
234 |
} |
235 |
else { |
236 |
while (r < origin || r >= bound) |
237 |
r = mix32(nextSeed()); |
238 |
} |
239 |
} |
240 |
return r; |
241 |
} |
242 |
|
243 |
/** |
244 |
* The form of nextDouble used by DoubleStream Spliterators. |
245 |
* |
246 |
* @param origin the least value, unless greater than bound |
247 |
* @param bound the upper bound (exclusive), must not equal origin |
248 |
* @return a pseudorandom value |
249 |
*/ |
250 |
final double internalNextDouble(double origin, double bound) { |
251 |
double r = (nextLong() >>> 11) * DOUBLE_UNIT; |
252 |
if (origin < bound) { |
253 |
r = r * (bound - origin) + origin; |
254 |
if (r >= bound) // correct for rounding |
255 |
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); |
256 |
} |
257 |
return r; |
258 |
} |
259 |
|
260 |
/** |
261 |
* Returns a pseudorandom {@code int} value. |
262 |
* |
263 |
* @return a pseudorandom {@code int} value |
264 |
*/ |
265 |
public int nextInt() { |
266 |
return mix32(nextSeed()); |
267 |
} |
268 |
|
269 |
/** |
270 |
* Returns a pseudorandom {@code int} value between zero (inclusive) |
271 |
* and the specified bound (exclusive). |
272 |
* |
273 |
* @param bound the upper bound (exclusive). Must be positive. |
274 |
* @return a pseudorandom {@code int} value between zero |
275 |
* (inclusive) and the bound (exclusive) |
276 |
* @throws IllegalArgumentException if {@code bound} is not positive |
277 |
*/ |
278 |
public int nextInt(int bound) { |
279 |
if (bound <= 0) |
280 |
throw new IllegalArgumentException(BAD_BOUND); |
281 |
int r = mix32(nextSeed()); |
282 |
int m = bound - 1; |
283 |
if ((bound & m) == 0) // power of two |
284 |
r &= m; |
285 |
else { // reject over-represented candidates |
286 |
for (int u = r >>> 1; |
287 |
u + m - (r = u % bound) < 0; |
288 |
u = mix32(nextSeed()) >>> 1) |
289 |
; |
290 |
} |
291 |
return r; |
292 |
} |
293 |
|
294 |
/** |
295 |
* Returns a pseudorandom {@code int} value between the specified |
296 |
* origin (inclusive) and the specified bound (exclusive). |
297 |
* |
298 |
* @param origin the least value returned |
299 |
* @param bound the upper bound (exclusive) |
300 |
* @return a pseudorandom {@code int} value between the origin |
301 |
* (inclusive) and the bound (exclusive) |
302 |
* @throws IllegalArgumentException if {@code origin} is greater than |
303 |
* or equal to {@code bound} |
304 |
*/ |
305 |
public int nextInt(int origin, int bound) { |
306 |
if (origin >= bound) |
307 |
throw new IllegalArgumentException(BAD_RANGE); |
308 |
return internalNextInt(origin, bound); |
309 |
} |
310 |
|
311 |
/** |
312 |
* Returns a pseudorandom {@code long} value. |
313 |
* |
314 |
* @return a pseudorandom {@code long} value |
315 |
*/ |
316 |
public long nextLong() { |
317 |
return mix64(nextSeed()); |
318 |
} |
319 |
|
320 |
/** |
321 |
* Returns a pseudorandom {@code long} value between zero (inclusive) |
322 |
* and the specified bound (exclusive). |
323 |
* |
324 |
* @param bound the upper bound (exclusive). Must be positive. |
325 |
* @return a pseudorandom {@code long} value between zero |
326 |
* (inclusive) and the bound (exclusive) |
327 |
* @throws IllegalArgumentException if {@code bound} is not positive |
328 |
*/ |
329 |
public long nextLong(long bound) { |
330 |
if (bound <= 0) |
331 |
throw new IllegalArgumentException(BAD_BOUND); |
332 |
long r = mix64(nextSeed()); |
333 |
long m = bound - 1; |
334 |
if ((bound & m) == 0L) // power of two |
335 |
r &= m; |
336 |
else { // reject over-represented candidates |
337 |
for (long u = r >>> 1; |
338 |
u + m - (r = u % bound) < 0L; |
339 |
u = mix64(nextSeed()) >>> 1) |
340 |
; |
341 |
} |
342 |
return r; |
343 |
} |
344 |
|
345 |
/** |
346 |
* Returns a pseudorandom {@code long} value between the specified |
347 |
* origin (inclusive) and the specified bound (exclusive). |
348 |
* |
349 |
* @param origin the least value returned |
350 |
* @param bound the upper bound (exclusive) |
351 |
* @return a pseudorandom {@code long} value between the origin |
352 |
* (inclusive) and the bound (exclusive) |
353 |
* @throws IllegalArgumentException if {@code origin} is greater than |
354 |
* or equal to {@code bound} |
355 |
*/ |
356 |
public long nextLong(long origin, long bound) { |
357 |
if (origin >= bound) |
358 |
throw new IllegalArgumentException(BAD_RANGE); |
359 |
return internalNextLong(origin, bound); |
360 |
} |
361 |
|
362 |
/** |
363 |
* Returns a pseudorandom {@code double} value between zero |
364 |
* (inclusive) and one (exclusive). |
365 |
* |
366 |
* @return a pseudorandom {@code double} value between zero |
367 |
* (inclusive) and one (exclusive) |
368 |
*/ |
369 |
public double nextDouble() { |
370 |
return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT; |
371 |
} |
372 |
|
373 |
/** |
374 |
* Returns a pseudorandom {@code double} value between 0.0 |
375 |
* (inclusive) and the specified bound (exclusive). |
376 |
* |
377 |
* @param bound the upper bound (exclusive). Must be positive. |
378 |
* @return a pseudorandom {@code double} value between zero |
379 |
* (inclusive) and the bound (exclusive) |
380 |
* @throws IllegalArgumentException if {@code bound} is not positive |
381 |
*/ |
382 |
public double nextDouble(double bound) { |
383 |
if (!(bound > 0.0)) |
384 |
throw new IllegalArgumentException(BAD_BOUND); |
385 |
double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound; |
386 |
return (result < bound) ? result : // correct for rounding |
387 |
Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1); |
388 |
} |
389 |
|
390 |
/** |
391 |
* Returns a pseudorandom {@code double} value between the specified |
392 |
* origin (inclusive) and bound (exclusive). |
393 |
* |
394 |
* @param origin the least value returned |
395 |
* @param bound the upper bound (exclusive) |
396 |
* @return a pseudorandom {@code double} value between the origin |
397 |
* (inclusive) and the bound (exclusive) |
398 |
* @throws IllegalArgumentException if {@code origin} is greater than |
399 |
* or equal to {@code bound} |
400 |
*/ |
401 |
public double nextDouble(double origin, double bound) { |
402 |
if (!(origin < bound)) |
403 |
throw new IllegalArgumentException(BAD_RANGE); |
404 |
return internalNextDouble(origin, bound); |
405 |
} |
406 |
|
407 |
/** |
408 |
* Returns a pseudorandom {@code boolean} value. |
409 |
* |
410 |
* @return a pseudorandom {@code boolean} value |
411 |
*/ |
412 |
public boolean nextBoolean() { |
413 |
return mix32(nextSeed()) < 0; |
414 |
} |
415 |
|
416 |
/** |
417 |
* Returns a pseudorandom {@code float} value between zero |
418 |
* (inclusive) and one (exclusive). |
419 |
* |
420 |
* @return a pseudorandom {@code float} value between zero |
421 |
* (inclusive) and one (exclusive) |
422 |
*/ |
423 |
public float nextFloat() { |
424 |
return (mix32(nextSeed()) >>> 8) * FLOAT_UNIT; |
425 |
} |
426 |
|
427 |
public double nextGaussian() { |
428 |
// Use nextLocalGaussian instead of nextGaussian field |
429 |
Double d = nextLocalGaussian.get(); |
430 |
if (d != null) { |
431 |
nextLocalGaussian.set(null); |
432 |
return d.doubleValue(); |
433 |
} |
434 |
double v1, v2, s; |
435 |
do { |
436 |
v1 = 2 * nextDouble() - 1; // between -1 and 1 |
437 |
v2 = 2 * nextDouble() - 1; // between -1 and 1 |
438 |
s = v1 * v1 + v2 * v2; |
439 |
} while (s >= 1 || s == 0); |
440 |
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
441 |
nextLocalGaussian.set(Double.valueOf(v2 * multiplier)); |
442 |
return v1 * multiplier; |
443 |
} |
444 |
|
445 |
// stream methods, coded in a way intended to better isolate for |
446 |
// maintenance purposes the small differences across forms. |
447 |
|
448 |
/** |
449 |
* Returns a stream producing the given {@code streamSize} number of |
450 |
* pseudorandom {@code int} values. |
451 |
* |
452 |
* @param streamSize the number of values to generate |
453 |
* @return a stream of pseudorandom {@code int} values |
454 |
* @throws IllegalArgumentException if {@code streamSize} is |
455 |
* less than zero |
456 |
* @since 1.8 |
457 |
*/ |
458 |
public IntStream ints(long streamSize) { |
459 |
if (streamSize < 0L) |
460 |
throw new IllegalArgumentException(BAD_SIZE); |
461 |
return StreamSupport.intStream |
462 |
(new RandomIntsSpliterator |
463 |
(0L, streamSize, Integer.MAX_VALUE, 0), |
464 |
false); |
465 |
} |
466 |
|
467 |
/** |
468 |
* Returns an effectively unlimited stream of pseudorandom {@code int} |
469 |
* values. |
470 |
* |
471 |
* @implNote This method is implemented to be equivalent to {@code |
472 |
* ints(Long.MAX_VALUE)}. |
473 |
* |
474 |
* @return a stream of pseudorandom {@code int} values |
475 |
* @since 1.8 |
476 |
*/ |
477 |
public IntStream ints() { |
478 |
return StreamSupport.intStream |
479 |
(new RandomIntsSpliterator |
480 |
(0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), |
481 |
false); |
482 |
} |
483 |
|
484 |
/** |
485 |
* Returns a stream producing the given {@code streamSize} number |
486 |
* of pseudorandom {@code int} values, each conforming to the given |
487 |
* origin (inclusive) and bound (exclusive). |
488 |
* |
489 |
* @param streamSize the number of values to generate |
490 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
491 |
* @param randomNumberBound the bound (exclusive) of each random value |
492 |
* @return a stream of pseudorandom {@code int} values, |
493 |
* each with the given origin (inclusive) and bound (exclusive) |
494 |
* @throws IllegalArgumentException if {@code streamSize} is |
495 |
* less than zero, or {@code randomNumberOrigin} |
496 |
* is greater than or equal to {@code randomNumberBound} |
497 |
* @since 1.8 |
498 |
*/ |
499 |
public IntStream ints(long streamSize, int randomNumberOrigin, |
500 |
int randomNumberBound) { |
501 |
if (streamSize < 0L) |
502 |
throw new IllegalArgumentException(BAD_SIZE); |
503 |
if (randomNumberOrigin >= randomNumberBound) |
504 |
throw new IllegalArgumentException(BAD_RANGE); |
505 |
return StreamSupport.intStream |
506 |
(new RandomIntsSpliterator |
507 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
508 |
false); |
509 |
} |
510 |
|
511 |
/** |
512 |
* Returns an effectively unlimited stream of pseudorandom {@code |
513 |
* int} values, each conforming to the given origin (inclusive) and bound |
514 |
* (exclusive). |
515 |
* |
516 |
* @implNote This method is implemented to be equivalent to {@code |
517 |
* ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
518 |
* |
519 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
520 |
* @param randomNumberBound the bound (exclusive) of each random value |
521 |
* @return a stream of pseudorandom {@code int} values, |
522 |
* each with the given origin (inclusive) and bound (exclusive) |
523 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
524 |
* is greater than or equal to {@code randomNumberBound} |
525 |
* @since 1.8 |
526 |
*/ |
527 |
public IntStream ints(int randomNumberOrigin, int randomNumberBound) { |
528 |
if (randomNumberOrigin >= randomNumberBound) |
529 |
throw new IllegalArgumentException(BAD_RANGE); |
530 |
return StreamSupport.intStream |
531 |
(new RandomIntsSpliterator |
532 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
533 |
false); |
534 |
} |
535 |
|
536 |
/** |
537 |
* Returns a stream producing the given {@code streamSize} number of |
538 |
* pseudorandom {@code long} values. |
539 |
* |
540 |
* @param streamSize the number of values to generate |
541 |
* @return a stream of pseudorandom {@code long} values |
542 |
* @throws IllegalArgumentException if {@code streamSize} is |
543 |
* less than zero |
544 |
* @since 1.8 |
545 |
*/ |
546 |
public LongStream longs(long streamSize) { |
547 |
if (streamSize < 0L) |
548 |
throw new IllegalArgumentException(BAD_SIZE); |
549 |
return StreamSupport.longStream |
550 |
(new RandomLongsSpliterator |
551 |
(0L, streamSize, Long.MAX_VALUE, 0L), |
552 |
false); |
553 |
} |
554 |
|
555 |
/** |
556 |
* Returns an effectively unlimited stream of pseudorandom {@code long} |
557 |
* values. |
558 |
* |
559 |
* @implNote This method is implemented to be equivalent to {@code |
560 |
* longs(Long.MAX_VALUE)}. |
561 |
* |
562 |
* @return a stream of pseudorandom {@code long} values |
563 |
* @since 1.8 |
564 |
*/ |
565 |
public LongStream longs() { |
566 |
return StreamSupport.longStream |
567 |
(new RandomLongsSpliterator |
568 |
(0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), |
569 |
false); |
570 |
} |
571 |
|
572 |
/** |
573 |
* Returns a stream producing the given {@code streamSize} number of |
574 |
* pseudorandom {@code long}, each conforming to the given origin |
575 |
* (inclusive) and bound (exclusive). |
576 |
* |
577 |
* @param streamSize the number of values to generate |
578 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
579 |
* @param randomNumberBound the bound (exclusive) of each random value |
580 |
* @return a stream of pseudorandom {@code long} values, |
581 |
* each with the given origin (inclusive) and bound (exclusive) |
582 |
* @throws IllegalArgumentException if {@code streamSize} is |
583 |
* less than zero, or {@code randomNumberOrigin} |
584 |
* is greater than or equal to {@code randomNumberBound} |
585 |
* @since 1.8 |
586 |
*/ |
587 |
public LongStream longs(long streamSize, long randomNumberOrigin, |
588 |
long randomNumberBound) { |
589 |
if (streamSize < 0L) |
590 |
throw new IllegalArgumentException(BAD_SIZE); |
591 |
if (randomNumberOrigin >= randomNumberBound) |
592 |
throw new IllegalArgumentException(BAD_RANGE); |
593 |
return StreamSupport.longStream |
594 |
(new RandomLongsSpliterator |
595 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
596 |
false); |
597 |
} |
598 |
|
599 |
/** |
600 |
* Returns an effectively unlimited stream of pseudorandom {@code |
601 |
* long} values, each conforming to the given origin (inclusive) and bound |
602 |
* (exclusive). |
603 |
* |
604 |
* @implNote This method is implemented to be equivalent to {@code |
605 |
* longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
606 |
* |
607 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
608 |
* @param randomNumberBound the bound (exclusive) of each random value |
609 |
* @return a stream of pseudorandom {@code long} values, |
610 |
* each with the given origin (inclusive) and bound (exclusive) |
611 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
612 |
* is greater than or equal to {@code randomNumberBound} |
613 |
* @since 1.8 |
614 |
*/ |
615 |
public LongStream longs(long randomNumberOrigin, long randomNumberBound) { |
616 |
if (randomNumberOrigin >= randomNumberBound) |
617 |
throw new IllegalArgumentException(BAD_RANGE); |
618 |
return StreamSupport.longStream |
619 |
(new RandomLongsSpliterator |
620 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
621 |
false); |
622 |
} |
623 |
|
624 |
/** |
625 |
* Returns a stream producing the given {@code streamSize} number of |
626 |
* pseudorandom {@code double} values, each between zero |
627 |
* (inclusive) and one (exclusive). |
628 |
* |
629 |
* @param streamSize the number of values to generate |
630 |
* @return a stream of {@code double} values |
631 |
* @throws IllegalArgumentException if {@code streamSize} is |
632 |
* less than zero |
633 |
* @since 1.8 |
634 |
*/ |
635 |
public DoubleStream doubles(long streamSize) { |
636 |
if (streamSize < 0L) |
637 |
throw new IllegalArgumentException(BAD_SIZE); |
638 |
return StreamSupport.doubleStream |
639 |
(new RandomDoublesSpliterator |
640 |
(0L, streamSize, Double.MAX_VALUE, 0.0), |
641 |
false); |
642 |
} |
643 |
|
644 |
/** |
645 |
* Returns an effectively unlimited stream of pseudorandom {@code |
646 |
* double} values, each between zero (inclusive) and one |
647 |
* (exclusive). |
648 |
* |
649 |
* @implNote This method is implemented to be equivalent to {@code |
650 |
* doubles(Long.MAX_VALUE)}. |
651 |
* |
652 |
* @return a stream of pseudorandom {@code double} values |
653 |
* @since 1.8 |
654 |
*/ |
655 |
public DoubleStream doubles() { |
656 |
return StreamSupport.doubleStream |
657 |
(new RandomDoublesSpliterator |
658 |
(0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), |
659 |
false); |
660 |
} |
661 |
|
662 |
/** |
663 |
* Returns a stream producing the given {@code streamSize} number of |
664 |
* pseudorandom {@code double} values, each conforming to the given origin |
665 |
* (inclusive) and bound (exclusive). |
666 |
* |
667 |
* @param streamSize the number of values to generate |
668 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
669 |
* @param randomNumberBound the bound (exclusive) of each random value |
670 |
* @return a stream of pseudorandom {@code double} values, |
671 |
* each with the given origin (inclusive) and bound (exclusive) |
672 |
* @throws IllegalArgumentException if {@code streamSize} is |
673 |
* less than zero, or {@code randomNumberOrigin} |
674 |
* is greater than or equal to {@code randomNumberBound} |
675 |
* @since 1.8 |
676 |
*/ |
677 |
public DoubleStream doubles(long streamSize, double randomNumberOrigin, |
678 |
double randomNumberBound) { |
679 |
if (streamSize < 0L) |
680 |
throw new IllegalArgumentException(BAD_SIZE); |
681 |
if (!(randomNumberOrigin < randomNumberBound)) |
682 |
throw new IllegalArgumentException(BAD_RANGE); |
683 |
return StreamSupport.doubleStream |
684 |
(new RandomDoublesSpliterator |
685 |
(0L, streamSize, randomNumberOrigin, randomNumberBound), |
686 |
false); |
687 |
} |
688 |
|
689 |
/** |
690 |
* Returns an effectively unlimited stream of pseudorandom {@code |
691 |
* double} values, each conforming to the given origin (inclusive) and bound |
692 |
* (exclusive). |
693 |
* |
694 |
* @implNote This method is implemented to be equivalent to {@code |
695 |
* doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}. |
696 |
* |
697 |
* @param randomNumberOrigin the origin (inclusive) of each random value |
698 |
* @param randomNumberBound the bound (exclusive) of each random value |
699 |
* @return a stream of pseudorandom {@code double} values, |
700 |
* each with the given origin (inclusive) and bound (exclusive) |
701 |
* @throws IllegalArgumentException if {@code randomNumberOrigin} |
702 |
* is greater than or equal to {@code randomNumberBound} |
703 |
* @since 1.8 |
704 |
*/ |
705 |
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { |
706 |
if (!(randomNumberOrigin < randomNumberBound)) |
707 |
throw new IllegalArgumentException(BAD_RANGE); |
708 |
return StreamSupport.doubleStream |
709 |
(new RandomDoublesSpliterator |
710 |
(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), |
711 |
false); |
712 |
} |
713 |
|
714 |
/** |
715 |
* Spliterator for int streams. We multiplex the four int |
716 |
* versions into one class by treating a bound less than origin as |
717 |
* unbounded, and also by treating "infinite" as equivalent to |
718 |
* Long.MAX_VALUE. For splits, it uses the standard divide-by-two |
719 |
* approach. The long and double versions of this class are |
720 |
* identical except for types. |
721 |
*/ |
722 |
private static final class RandomIntsSpliterator |
723 |
implements Spliterator.OfInt { |
724 |
long index; |
725 |
final long fence; |
726 |
final int origin; |
727 |
final int bound; |
728 |
RandomIntsSpliterator(long index, long fence, |
729 |
int origin, int bound) { |
730 |
this.index = index; this.fence = fence; |
731 |
this.origin = origin; this.bound = bound; |
732 |
} |
733 |
|
734 |
public RandomIntsSpliterator trySplit() { |
735 |
long i = index, m = (i + fence) >>> 1; |
736 |
return (m <= i) ? null : |
737 |
new RandomIntsSpliterator(i, index = m, origin, bound); |
738 |
} |
739 |
|
740 |
public long estimateSize() { |
741 |
return fence - index; |
742 |
} |
743 |
|
744 |
public int characteristics() { |
745 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
746 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
747 |
} |
748 |
|
749 |
public boolean tryAdvance(IntConsumer consumer) { |
750 |
if (consumer == null) throw new NullPointerException(); |
751 |
long i = index, f = fence; |
752 |
if (i < f) { |
753 |
consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound)); |
754 |
index = i + 1; |
755 |
return true; |
756 |
} |
757 |
return false; |
758 |
} |
759 |
|
760 |
public void forEachRemaining(IntConsumer consumer) { |
761 |
if (consumer == null) throw new NullPointerException(); |
762 |
long i = index, f = fence; |
763 |
if (i < f) { |
764 |
index = f; |
765 |
int o = origin, b = bound; |
766 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
767 |
do { |
768 |
consumer.accept(rng.internalNextInt(o, b)); |
769 |
} while (++i < f); |
770 |
} |
771 |
} |
772 |
} |
773 |
|
774 |
/** |
775 |
* Spliterator for long streams. |
776 |
*/ |
777 |
private static final class RandomLongsSpliterator |
778 |
implements Spliterator.OfLong { |
779 |
long index; |
780 |
final long fence; |
781 |
final long origin; |
782 |
final long bound; |
783 |
RandomLongsSpliterator(long index, long fence, |
784 |
long origin, long bound) { |
785 |
this.index = index; this.fence = fence; |
786 |
this.origin = origin; this.bound = bound; |
787 |
} |
788 |
|
789 |
public RandomLongsSpliterator trySplit() { |
790 |
long i = index, m = (i + fence) >>> 1; |
791 |
return (m <= i) ? null : |
792 |
new RandomLongsSpliterator(i, index = m, origin, bound); |
793 |
} |
794 |
|
795 |
public long estimateSize() { |
796 |
return fence - index; |
797 |
} |
798 |
|
799 |
public int characteristics() { |
800 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
801 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
802 |
} |
803 |
|
804 |
public boolean tryAdvance(LongConsumer consumer) { |
805 |
if (consumer == null) throw new NullPointerException(); |
806 |
long i = index, f = fence; |
807 |
if (i < f) { |
808 |
consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound)); |
809 |
index = i + 1; |
810 |
return true; |
811 |
} |
812 |
return false; |
813 |
} |
814 |
|
815 |
public void forEachRemaining(LongConsumer consumer) { |
816 |
if (consumer == null) throw new NullPointerException(); |
817 |
long i = index, f = fence; |
818 |
if (i < f) { |
819 |
index = f; |
820 |
long o = origin, b = bound; |
821 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
822 |
do { |
823 |
consumer.accept(rng.internalNextLong(o, b)); |
824 |
} while (++i < f); |
825 |
} |
826 |
} |
827 |
|
828 |
} |
829 |
|
830 |
/** |
831 |
* Spliterator for double streams. |
832 |
*/ |
833 |
private static final class RandomDoublesSpliterator |
834 |
implements Spliterator.OfDouble { |
835 |
long index; |
836 |
final long fence; |
837 |
final double origin; |
838 |
final double bound; |
839 |
RandomDoublesSpliterator(long index, long fence, |
840 |
double origin, double bound) { |
841 |
this.index = index; this.fence = fence; |
842 |
this.origin = origin; this.bound = bound; |
843 |
} |
844 |
|
845 |
public RandomDoublesSpliterator trySplit() { |
846 |
long i = index, m = (i + fence) >>> 1; |
847 |
return (m <= i) ? null : |
848 |
new RandomDoublesSpliterator(i, index = m, origin, bound); |
849 |
} |
850 |
|
851 |
public long estimateSize() { |
852 |
return fence - index; |
853 |
} |
854 |
|
855 |
public int characteristics() { |
856 |
return (Spliterator.SIZED | Spliterator.SUBSIZED | |
857 |
Spliterator.NONNULL | Spliterator.IMMUTABLE); |
858 |
} |
859 |
|
860 |
public boolean tryAdvance(DoubleConsumer consumer) { |
861 |
if (consumer == null) throw new NullPointerException(); |
862 |
long i = index, f = fence; |
863 |
if (i < f) { |
864 |
consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound)); |
865 |
index = i + 1; |
866 |
return true; |
867 |
} |
868 |
return false; |
869 |
} |
870 |
|
871 |
public void forEachRemaining(DoubleConsumer consumer) { |
872 |
if (consumer == null) throw new NullPointerException(); |
873 |
long i = index, f = fence; |
874 |
if (i < f) { |
875 |
index = f; |
876 |
double o = origin, b = bound; |
877 |
ThreadLocalRandom rng = ThreadLocalRandom.current(); |
878 |
do { |
879 |
consumer.accept(rng.internalNextDouble(o, b)); |
880 |
} while (++i < f); |
881 |
} |
882 |
} |
883 |
} |
884 |
|
885 |
|
886 |
// Within-package utilities |
887 |
|
888 |
/* |
889 |
* Descriptions of the usages of the methods below can be found in |
890 |
* the classes that use them. Briefly, a thread's "probe" value is |
891 |
* a non-zero hash code that (probably) does not collide with |
892 |
* other existing threads with respect to any power of two |
893 |
* collision space. When it does collide, it is pseudo-randomly |
894 |
* adjusted (using a Marsaglia XorShift). The nextSecondarySeed |
895 |
* method is used in the same contexts as ThreadLocalRandom, but |
896 |
* only for transient usages such as random adaptive spin/block |
897 |
* sequences for which a cheap RNG suffices and for which it could |
898 |
* in principle disrupt user-visible statistical properties of the |
899 |
* main ThreadLocalRandom if we were to use it. |
900 |
* |
901 |
* Note: Because of package-protection issues, versions of some |
902 |
* these methods also appear in some subpackage classes. |
903 |
*/ |
904 |
|
905 |
/** |
906 |
* Returns the probe value for the current thread without forcing |
907 |
* initialization. Note that invoking ThreadLocalRandom.current() |
908 |
* can be used to force initialization on zero return. |
909 |
*/ |
910 |
static final int getProbe() { |
911 |
return U.getInt(Thread.currentThread(), PROBE); |
912 |
} |
913 |
|
914 |
/** |
915 |
* Pseudo-randomly advances and records the given probe value for the |
916 |
* given thread. |
917 |
*/ |
918 |
static final int advanceProbe(int probe) { |
919 |
probe ^= probe << 13; // xorshift |
920 |
probe ^= probe >>> 17; |
921 |
probe ^= probe << 5; |
922 |
U.putInt(Thread.currentThread(), PROBE, probe); |
923 |
return probe; |
924 |
} |
925 |
|
926 |
/** |
927 |
* Returns the pseudo-randomly initialized or updated secondary seed. |
928 |
*/ |
929 |
static final int nextSecondarySeed() { |
930 |
int r; |
931 |
Thread t = Thread.currentThread(); |
932 |
if ((r = U.getInt(t, SECONDARY)) != 0) { |
933 |
r ^= r << 13; // xorshift |
934 |
r ^= r >>> 17; |
935 |
r ^= r << 5; |
936 |
} |
937 |
else if ((r = mix32(seeder.getAndAdd(SEEDER_INCREMENT))) == 0) |
938 |
r = 1; // avoid zero |
939 |
U.putInt(t, SECONDARY, r); |
940 |
return r; |
941 |
} |
942 |
|
943 |
// Support for other package-private ThreadLocal access |
944 |
|
945 |
/** |
946 |
* Erases ThreadLocals by nulling out Thread maps. |
947 |
*/ |
948 |
static final void eraseThreadLocals(Thread thread) { |
949 |
U.putObject(thread, THREADLOCALS, null); |
950 |
U.putObject(thread, INHERITABLETHREADLOCALS, null); |
951 |
} |
952 |
|
953 |
static final void setInheritedAccessControlContext(Thread thread, |
954 |
AccessControlContext acc) { |
955 |
U.putObjectRelease(thread, INHERITEDACCESSCONTROLCONTEXT, acc); |
956 |
} |
957 |
|
958 |
// Serialization support |
959 |
|
960 |
private static final long serialVersionUID = -5851777807851030925L; |
961 |
|
962 |
/** |
963 |
* @serialField rnd long |
964 |
* seed for random computations |
965 |
* @serialField initialized boolean |
966 |
* always true |
967 |
*/ |
968 |
private static final ObjectStreamField[] serialPersistentFields = { |
969 |
new ObjectStreamField("rnd", long.class), |
970 |
new ObjectStreamField("initialized", boolean.class), |
971 |
}; |
972 |
|
973 |
/** |
974 |
* Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it). |
975 |
* @param s the stream |
976 |
* @throws java.io.IOException if an I/O error occurs |
977 |
*/ |
978 |
private void writeObject(java.io.ObjectOutputStream s) |
979 |
throws java.io.IOException { |
980 |
|
981 |
java.io.ObjectOutputStream.PutField fields = s.putFields(); |
982 |
fields.put("rnd", U.getLong(Thread.currentThread(), SEED)); |
983 |
fields.put("initialized", true); |
984 |
s.writeFields(); |
985 |
} |
986 |
|
987 |
/** |
988 |
* Returns the {@link #current() current} thread's {@code ThreadLocalRandom}. |
989 |
* @return the {@link #current() current} thread's {@code ThreadLocalRandom} |
990 |
*/ |
991 |
private Object readResolve() { |
992 |
return current(); |
993 |
} |
994 |
|
995 |
// Static initialization |
996 |
|
997 |
/** |
998 |
* The seed increment. |
999 |
*/ |
1000 |
private static final long GAMMA = 0x9e3779b97f4a7c15L; |
1001 |
|
1002 |
/** |
1003 |
* The increment for generating probe values. |
1004 |
*/ |
1005 |
private static final int PROBE_INCREMENT = 0x9e3779b9; |
1006 |
|
1007 |
/** |
1008 |
* The increment of seeder per new instance. |
1009 |
*/ |
1010 |
private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL; |
1011 |
|
1012 |
// Constants from SplittableRandom |
1013 |
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) |
1014 |
private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24) |
1015 |
|
1016 |
// IllegalArgumentException messages |
1017 |
static final String BAD_BOUND = "bound must be positive"; |
1018 |
static final String BAD_RANGE = "bound must be greater than origin"; |
1019 |
static final String BAD_SIZE = "size must be non-negative"; |
1020 |
|
1021 |
// Unsafe mechanics |
1022 |
private static final Unsafe U = Unsafe.getUnsafe(); |
1023 |
private static final long SEED; |
1024 |
private static final long PROBE; |
1025 |
private static final long SECONDARY; |
1026 |
private static final long THREADLOCALS; |
1027 |
private static final long INHERITABLETHREADLOCALS; |
1028 |
private static final long INHERITEDACCESSCONTROLCONTEXT; |
1029 |
static { |
1030 |
try { |
1031 |
SEED = U.objectFieldOffset |
1032 |
(Thread.class.getDeclaredField("threadLocalRandomSeed")); |
1033 |
PROBE = U.objectFieldOffset |
1034 |
(Thread.class.getDeclaredField("threadLocalRandomProbe")); |
1035 |
SECONDARY = U.objectFieldOffset |
1036 |
(Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); |
1037 |
THREADLOCALS = U.objectFieldOffset |
1038 |
(Thread.class.getDeclaredField("threadLocals")); |
1039 |
INHERITABLETHREADLOCALS = U.objectFieldOffset |
1040 |
(Thread.class.getDeclaredField("inheritableThreadLocals")); |
1041 |
INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset |
1042 |
(Thread.class.getDeclaredField("inheritedAccessControlContext")); |
1043 |
} catch (ReflectiveOperationException e) { |
1044 |
throw new Error(e); |
1045 |
} |
1046 |
} |
1047 |
|
1048 |
/** Rarely-used holder for the second of a pair of Gaussians */ |
1049 |
private static final ThreadLocal<Double> nextLocalGaussian = |
1050 |
new ThreadLocal<>(); |
1051 |
|
1052 |
/** Generates per-thread initialization/probe field */ |
1053 |
private static final AtomicInteger probeGenerator = new AtomicInteger(); |
1054 |
|
1055 |
/** The common ThreadLocalRandom */ |
1056 |
static final ThreadLocalRandom instance = new ThreadLocalRandom(); |
1057 |
|
1058 |
/** |
1059 |
* The next seed for default constructors. |
1060 |
*/ |
1061 |
private static final AtomicLong seeder |
1062 |
= new AtomicLong(mix64(System.currentTimeMillis()) ^ |
1063 |
mix64(System.nanoTime())); |
1064 |
|
1065 |
// at end of <clinit> to survive static initialization circularity |
1066 |
static { |
1067 |
if (java.security.AccessController.doPrivileged( |
1068 |
new java.security.PrivilegedAction<>() { |
1069 |
public Boolean run() { |
1070 |
return Boolean.getBoolean("java.util.secureRandomSeed"); |
1071 |
}})) { |
1072 |
byte[] seedBytes = java.security.SecureRandom.getSeed(8); |
1073 |
long s = (long)seedBytes[0] & 0xffL; |
1074 |
for (int i = 1; i < 8; ++i) |
1075 |
s = (s << 8) | ((long)seedBytes[i] & 0xffL); |
1076 |
seeder.set(s); |
1077 |
} |
1078 |
} |
1079 |
} |