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