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