forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplittableRandom.java
1116 lines (1015 loc) · 45.4 KB
/
SplittableRandom.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.StreamSupport;
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
* generate subtasks. Class {@code SplittableRandom} supports methods for
* producing pseudorandom numbers of type {@code int}, {@code long},
* and {@code double} with similar usages as for class
* {@link java.util.Random} but differs in the following ways:
*
* <ul>
*
* <li>Series of generated values pass the DieHarder suite testing
* independence and uniformity properties of random number generators.
* (Most recently validated with <a
* href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
* 3.31.1</a>.) These tests validate only the methods for certain
* types and ranges, but similar properties are expected to hold, at
* least approximately, for others as well. The <em>period</em>
* (length of any series of generated values before it repeats) is at
* least 2<sup>64</sup>.
*
* <li>Method {@link #split} constructs and returns a new
* SplittableRandom instance that shares no mutable state with the
* current instance. However, with very high probability, the
* values collectively generated by the two objects have the same
* statistical properties as if the same quantity of values were
* generated by a single thread using a single {@code
* SplittableRandom} object.
*
* <li>Instances of SplittableRandom are <em>not</em> thread-safe.
* They are designed to be split, not shared, across threads. For
* example, a {@link java.util.concurrent.ForkJoinTask
* fork/join-style} computation using random numbers might include a
* construction of the form {@code new
* Subtask(aSplittableRandom.split()).fork()}.
*
* <li>This class provides additional methods for generating random
* streams, that employ the above techniques when used in {@code
* stream.parallel()} mode.
*
* </ul>
*
* <p>Instances of {@code SplittableRandom} are not cryptographically
* secure. Consider instead using {@link java.security.SecureRandom}
* in security-sensitive applications. Additionally,
* default-constructed instances do not use a cryptographically random
* seed unless the {@linkplain System#getProperty system property}
* {@code java.util.secureRandomSeed} is set to {@code true}.
*
* @author Guy Steele
* @author Doug Lea
* @since 1.8
*/
/*
* 伪随机数生成器
*
* 非线程安全
* 适用于少数单线程场景
*
* 支持使用内置种子计算的原始种子
* 支持自定义原始种子
* 支持使用安全种子(设置运行参数-Djava.util.secureRandomSeed=true)
*/
public final class SplittableRandom {
/*
* Implementation Overview.
*
* This algorithm was inspired by the "DotMix" algorithm by
* Leiserson, Schardl, and Sukha "Deterministic Parallel
* Random-Number Generation for Dynamic-Multithreading Platforms",
* PPoPP 2012, as well as those in "Parallel random numbers: as
* easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It
* differs mainly in simplifying and cheapening operations.
*
* The primary update step (method nextSeed()) is to add a
* constant ("gamma") to the current (64 bit) seed, forming a
* simple sequence. The seed and the gamma values for any two
* SplittableRandom instances are highly likely to be different.
*
* Methods nextLong, nextInt, and derivatives do not return the
* sequence (seed) values, but instead a hash-like bit-mix of
* their bits, producing more independently distributed sequences.
* For nextLong, the mix64 function is based on David Stafford's
* (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
* "Mix13" variant of the "64-bit finalizer" function in Austin
* Appleby's MurmurHash3 algorithm (see
* http://code.google.com/p/smhasher/wiki/MurmurHash3). The mix32
* function is based on Stafford's Mix04 mix function, but returns
* the upper 32 bits cast as int.
*
* The split operation uses the current generator to form the seed
* and gamma for another SplittableRandom. To conservatively
* avoid potential correlations between seed and value generation,
* gamma selection (method mixGamma) uses different
* (Murmurhash3's) mix constants. To avoid potential weaknesses
* in bit-mixing transformations, we restrict gammas to odd values
* with at least 24 0-1 or 1-0 bit transitions. Rather than
* rejecting candidates with too few or too many bits set, method
* mixGamma flips some bits (which has the effect of mapping at
* most 4 to any given gamma value). This reduces the effective
* set of 64bit odd gamma values by about 2%, and serves as an
* automated screening for sequence constant selection that is
* left as an empirical decision in some other hashing and crypto
* algorithms.
*
* The resulting generator thus transforms a sequence in which
* (typically) many bits change on each step, with an inexpensive
* mixer with good (but less than cryptographically secure)
* avalanching.
*
* The default (no-argument) constructor, in essence, invokes
* split() for a common "defaultGen" SplittableRandom. Unlike
* other cases, this split must be performed in a thread-safe
* manner, so we use an AtomicLong to represent the seed rather
* than use an explicit SplittableRandom. To bootstrap the
* defaultGen, we start off using a seed based on current time
* unless the java.util.secureRandomSeed property is set. This
* serves as a slimmed-down (and insecure) variant of SecureRandom
* that also avoids stalls that may occur when using /dev/random.
*
* It is a relatively simple matter to apply the basic design here
* to use 128 bit seeds. However, emulating 128bit arithmetic and
* carrying around twice the state add more overhead than appears
* warranted for current usages.
*
* File organization: First the non-public methods that constitute
* the main algorithm, then the main public methods, followed by
* some custom spliterator classes needed for stream methods.
*/
// IllegalArgumentException messages
static final String BAD_BOUND = "bound must be positive";
static final String BAD_RANGE = "bound must be greater than origin";
static final String BAD_SIZE = "size must be non-negative";
/*▼ 内置种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
/**
* The seed generator for default constructors.
*/
// 内置种子,用来生成原始种子
private static final AtomicLong defaultGen = new AtomicLong(mix64(System.currentTimeMillis()) ^ mix64(System.nanoTime()));
/*▲ 内置种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
/*▼ 原始种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
/**
* The seed. Updated only via method nextSeed.
*/
// 原始种子,用来生成随机数
private long seed;
/**
* The step value.
*/
// 用于更新原始种子的步长
private final long gamma;
/*▲ 原始种子 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
/**
* The golden ratio scaled to 64bits, used as the initial gamma value for (unsplit) SplittableRandoms.
*/
private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
/**
* The least non-zero value returned by nextDouble(). This value
* is scaled by a random value of 53 bits to produce a result.
*/
// double值的二进制精度
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53);
// at end of <clinit> to survive static initialization circularity
static {
if(AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return Boolean.getBoolean("java.util.secureRandomSeed");
}
})) {
byte[] seedBytes = SecureRandom.getSeed(8);
long s = (long) seedBytes[0] & 0xffL;
for(int i = 1; i<8; ++i) {
s = (s << 8) | ((long) seedBytes[i] & 0xffL);
}
defaultGen.set(s);
}
}
/*▼ 构造方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new SplittableRandom instance that is likely to generate sequences of values
* that are statistically independent those of any other instances in the current program;
* and may, and typically does, vary across program invocations.
*/
public SplittableRandom() { // emulate defaultGen.split()
long s = defaultGen.getAndAdd(GOLDEN_GAMMA << 1);
this.seed = mix64(s);
this.gamma = mixGamma(s + GOLDEN_GAMMA);
}
/**
* Creates a new SplittableRandom instance using the specified
* initial seed. SplittableRandom instances created with the same
* seed in the same program generate identical sequences of values.
*
* @param seed the initial seed
*/
public SplittableRandom(long seed) {
this(seed, GOLDEN_GAMMA);
}
/**
* Internal constructor used by all others except default constructor.
*/
private SplittableRandom(long seed, long gamma) {
this.seed = seed;
this.gamma = gamma;
}
/*▲ 构造方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 种子 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructs and returns a new SplittableRandom instance that
* shares no mutable state with this instance. However, with very
* high probability, the set of values collectively generated by
* the two objects has the same statistical properties as if the
* same quantity of values were generated by a single thread using
* a single SplittableRandom object. Either or both of the two
* objects may be further split using the {@code split()} method,
* and the same expected statistical properties apply to the
* entire set of generators constructed by such recursive
* splitting.
*
* @return the new SplittableRandom instance
*/
// 获取SplittableRandom实例
public SplittableRandom split() {
return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
}
/**
* Adds gamma to seed.
*/
// 获取下一个种子
private long nextSeed() {
return seed += gamma;
}
/*▲ 种子 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 生成伪随机数 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Fills a user-supplied byte array with generated pseudorandom bytes.
*
* @param bytes the byte array to fill with pseudorandom bytes
*
* @throws NullPointerException if bytes is null
* @since 10
*/
// 随机填充一个byte数组,有正有负
public void nextBytes(byte[] bytes) {
int i = 0;
int len = bytes.length;
for(int words = len >> 3; words-->0; ) {
long rnd = nextLong();
for(int n = 8; n-->0; rnd >>>= Byte.SIZE)
bytes[i++] = (byte) rnd;
}
if(i<len) {
for(long rnd = nextLong(); i<len; rnd >>>= Byte.SIZE) {
bytes[i++] = (byte) rnd;
}
}
}
/**
* Returns a pseudorandom {@code int} value.
*
* @return a pseudorandom {@code int} value
*/
// 随机生成一个int值,有正有负
public int nextInt() {
return mix32(nextSeed());
}
/**
* Returns a pseudorandom {@code int} value between zero (inclusive)
* and the specified bound (exclusive).
*
* @param bound the upper bound (exclusive). Must be positive.
*
* @return a pseudorandom {@code int} value between zero
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code bound} is not positive
*/
// 随机生成一个[0, bound)之内的int值
public int nextInt(int bound) {
if(bound<=0) {
throw new IllegalArgumentException(BAD_BOUND);
}
// Specialize internalNextInt for origin 0
int r = mix32(nextSeed());
int m = bound - 1;
if((bound & m) == 0) { // power of two
r &= m;
} else { // reject over-represented candidates
for(int u = r >>> 1; u + m - (r = u % bound)<0; u = mix32(nextSeed()) >>> 1)
;
}
return r;
}
/**
* Returns a pseudorandom {@code int} value between the specified
* origin (inclusive) and the specified bound (exclusive).
*
* @param origin the least value returned
* @param bound the upper bound (exclusive)
*
* @return a pseudorandom {@code int} value between the origin
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
// 随机生成一个[origin, bound)之内的int值,有正有负
public int nextInt(int origin, int bound) {
if(origin >= bound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return internalNextInt(origin, bound);
}
/**
* Returns a pseudorandom {@code long} value.
*
* @return a pseudorandom {@code long} value
*/
// 随机生成一个long值,有正有负
public long nextLong() {
return mix64(nextSeed());
}
/**
* Returns a pseudorandom {@code long} value between zero (inclusive)
* and the specified bound (exclusive).
*
* @param bound the upper bound (exclusive). Must be positive.
*
* @return a pseudorandom {@code long} value between zero
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code bound} is not positive
*/
// 随机生成一个[0, bound)之内的long值
public long nextLong(long bound) {
if(bound<=0) {
throw new IllegalArgumentException(BAD_BOUND);
}
// Specialize internalNextLong for origin 0
long r = mix64(nextSeed());
long m = bound - 1;
if((bound & m) == 0L) { // power of two
r &= m;
} else { // reject over-represented candidates
for(long u = r >>> 1; u + m - (r = u % bound)<0L; u = mix64(nextSeed()) >>> 1)
;
}
return r;
}
/**
* Returns a pseudorandom {@code long} value between the specified
* origin (inclusive) and the specified bound (exclusive).
*
* @param origin the least value returned
* @param bound the upper bound (exclusive)
*
* @return a pseudorandom {@code long} value between the origin
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
// 随机生成一个[origin, bound)之内的long值,有正有负
public long nextLong(long origin, long bound) {
if(origin >= bound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return internalNextLong(origin, bound);
}
/**
* Returns a pseudorandom {@code double} value between zero
* (inclusive) and one (exclusive).
*
* @return a pseudorandom {@code double} value between zero
* (inclusive) and one (exclusive)
*/
// 随机生成一个[0, 1)之内的double值
public double nextDouble() {
return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
}
/**
* Returns a pseudorandom {@code double} value between 0.0
* (inclusive) and the specified bound (exclusive).
*
* @param bound the upper bound (exclusive). Must be positive.
*
* @return a pseudorandom {@code double} value between zero
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code bound} is not positive
*/
// 随机生成一个[0, bound)之内的double值
public double nextDouble(double bound) {
if(!(bound>0.0)) {
throw new IllegalArgumentException(BAD_BOUND);
}
double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
return (result<bound)
? result // correct for rounding
: Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
}
/**
* Returns a pseudorandom {@code double} value between the specified
* origin (inclusive) and bound (exclusive).
*
* @param origin the least value returned
* @param bound the upper bound (exclusive)
*
* @return a pseudorandom {@code double} value between the origin
* (inclusive) and the bound (exclusive)
*
* @throws IllegalArgumentException if {@code origin} is greater than
* or equal to {@code bound}
*/
// 随机生成一个[origin, bound)之内的double值,有正有负
public double nextDouble(double origin, double bound) {
if(!(origin<bound)) {
throw new IllegalArgumentException(BAD_RANGE);
}
return internalNextDouble(origin, bound);
}
/**
* Returns a pseudorandom {@code boolean} value.
*
* @return a pseudorandom {@code boolean} value
*/
// 随机生成一个boolean值
public boolean nextBoolean() {
return mix32(nextSeed())<0;
}
/*▲ 生成伪随机数 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 流 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an effectively unlimited stream of pseudorandom {@code int}
* values from this generator and/or one split from it.
*
* @return a stream of pseudorandom {@code int} values
*
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机int值
public IntStream ints() {
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0), false);
}
/**
* Returns a stream producing the given {@code streamSize} number
* of pseudorandom {@code int} values from this generator and/or
* one split from it.
*
* @param streamSize the number of values to generate
*
* @return a stream of pseudorandom {@code int} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
*/
// 返回的流可以生成streamSize个随机int值
public IntStream ints(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, Integer.MAX_VALUE, 0), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* int} values from this generator and/or one split from it; each value
* conforms to the given origin (inclusive) and bound (exclusive).
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code int} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机int值,取值范围是[randomNumberOrigin, randomNumberBound)
public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number
* of pseudorandom {@code int} values from this generator and/or one split
* from it; each value conforms to the given origin (inclusive) and bound
* (exclusive).
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code int} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
// 返回的流可以生成streamSize个随机int值,取值范围是[randomNumberOrigin, randomNumberBound)
public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* long} values from this generator and/or one split from it.
*
* @return a stream of pseudorandom {@code long} values
*
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机long值
public LongStream longs() {
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L), false);
}
/**
* Returns a stream producing the given {@code streamSize} number
* of pseudorandom {@code long} values from this generator and/or
* one split from it.
*
* @param streamSize the number of values to generate
*
* @return a stream of pseudorandom {@code long} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
*/
// 返回的流可以生成streamSize个随机long值
public LongStream longs(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, Long.MAX_VALUE, 0L), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* long} values from this generator and/or one split from it; each value
* conforms to the given origin (inclusive) and bound (exclusive).
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code long} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机long值,取值范围是[randomNumberOrigin, randomNumberBound)
public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code long} values from this generator and/or one split
* from it; each value conforms to the given origin (inclusive) and bound
* (exclusive).
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code long} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
// 返回的流可以生成streamSize个随机long值,取值范围是[randomNumberOrigin, randomNumberBound)
public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
if(randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* double} values from this generator and/or one split from it; each value
* is between zero (inclusive) and one (exclusive).
*
* @return a stream of pseudorandom {@code double} values
*
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机double值,取值范围是[0, 1)
public DoubleStream doubles() {
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code double} values from this generator and/or one split
* from it; each value is between zero (inclusive) and one (exclusive).
*
* @param streamSize the number of values to generate
*
* @return a stream of {@code double} values
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
*/
// 返回的流可以生成streamSize个随机double值,取值范围是[0, 1)
public DoubleStream doubles(long streamSize) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, streamSize, Double.MAX_VALUE, 0.0), false);
}
/**
* Returns an effectively unlimited stream of pseudorandom {@code
* double} values from this generator and/or one split from it; each value
* conforms to the given origin (inclusive) and bound (exclusive).
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code double} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*/
// 返回的流可以生成Long.MAX_VALUE个随机double值,取值范围是[randomNumberOrigin, randomNumberBound)
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
if(!(randomNumberOrigin<randomNumberBound)) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound), false);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* pseudorandom {@code double} values from this generator and/or one split
* from it; each value conforms to the given origin (inclusive) and bound
* (exclusive).
*
* @param streamSize the number of values to generate
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
*
* @return a stream of pseudorandom {@code double} values,
* each with the given origin (inclusive) and bound (exclusive)
*
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero, or {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
// 返回的流可以生成streamSize个随机double值,取值范围是[randomNumberOrigin, randomNumberBound)
public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) {
if(streamSize<0L) {
throw new IllegalArgumentException(BAD_SIZE);
}
if(!(randomNumberOrigin<randomNumberBound)) {
throw new IllegalArgumentException(BAD_RANGE);
}
return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound), false);
}
/*▲ 流 ████████████████████████████████████████████████████████████████████████████████┛ */
/*
* Internal versions of nextX methods used by streams, as well as
* the public nextX(origin, bound) methods. These exist mainly to
* avoid the need for multiple versions of stream spliterators
* across the different exported forms of streams.
*/
/**
* The form of nextInt used by IntStream Spliterators.
* Exactly the same as long version, except for types.
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的int值
final int internalNextInt(int origin, int bound) {
int r = mix32(nextSeed());
if (origin < bound) {
int n = bound - origin, m = n - 1;
if ((n & m) == 0)
r = (r & m) + origin;
else if (n > 0) {
for (int u = r >>> 1;
u + m - (r = u % n) < 0;
u = mix32(nextSeed()) >>> 1)
;
r += origin;
}
else {
while (r < origin || r >= bound)
r = mix32(nextSeed());
}
}
return r;
}
/**
* The form of nextLong used by LongStream Spliterators. If
* origin is greater than bound, acts as unbounded form of
* nextLong, else as bounded form.
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的long值
final long internalNextLong(long origin, long bound) {
/*
* Four Cases:
*
* 1. If the arguments indicate unbounded form, act as
* nextLong().
*
* 2. If the range is an exact power of two, apply the
* associated bit mask.
*
* 3. If the range is positive, loop to avoid potential bias
* when the implicit nextLong() bound (2<sup>64</sup>) is not
* evenly divisible by the range. The loop rejects candidates
* computed from otherwise over-represented values. The
* expected number of iterations under an ideal generator
* varies from 1 to 2, depending on the bound. The loop itself
* takes an unlovable form. Because the first candidate is
* already available, we need a break-in-the-middle
* construction, which is concisely but cryptically performed
* within the while-condition of a body-less for loop.
*
* 4. Otherwise, the range cannot be represented as a positive
* long. The loop repeatedly generates unbounded longs until
* obtaining a candidate meeting constraints (with an expected
* number of iterations of less than two).
*/
long r = mix64(nextSeed());
if (origin < bound) {
long n = bound - origin, m = n - 1;
if ((n & m) == 0L) // power of two
r = (r & m) + origin;
else if (n > 0L) { // reject over-represented candidates
for (long u = r >>> 1; // ensure nonnegative
u + m - (r = u % n) < 0L; // rejection check
u = mix64(nextSeed()) >>> 1) // retry
;
r += origin;
}
else { // range not representable as long
while (r < origin || r >= bound)
r = mix64(nextSeed());
}
}
return r;
}
/**
* The form of nextDouble used by DoubleStream Spliterators.
*
* @param origin the least value, unless greater than bound
* @param bound the upper bound (exclusive), must not equal origin
* @return a pseudorandom value
*/
// 随机生成一个[origin, bound)之内的double值
final double internalNextDouble(double origin, double bound) {
double r = (nextLong() >>> 11) * DOUBLE_UNIT;
if (origin < bound) {
r = r * (bound - origin) + origin;
if (r >= bound) // correct for rounding
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
}
return r;
}
/**
* Returns the 32 high bits of Stafford variant 4 mix64 function as int.
*/
private static int mix32(long z) {
z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L;
return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
}
/**
* Computes Stafford variant 13 of 64bit mix function.
*/
private static long mix64(long z) {
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
return z ^ (z >>> 31);
}
/**
* Returns the gamma value to use for a new split instance.
*/
private static long mixGamma(long z) {
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
z = (z ^ (z >>> 33)) | 1L; // force to be odd
int n = Long.bitCount(z ^ (z >>> 1)); // ensure enough transitions
return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
}
/**
* Spliterator for int streams. We multiplex the four int
* versions into one class by treating a bound less than origin as
* unbounded, and also by treating "infinite" as equivalent to
* Long.MAX_VALUE. For splits, it uses the standard divide-by-two
* approach. The long and double versions of this class are
* identical except for types.
*/
// 可以随机生成int元素的流
private static final class RandomIntsSpliterator implements Spliterator.OfInt {
final SplittableRandom rng;
// 随机数数量:fence-index
long index;
final long fence;
// 随机数取值范围:[origin, bound)
final int origin;
final int bound;
RandomIntsSpliterator(SplittableRandom rng, long index, long fence, int origin, int bound) {
this.rng = rng;
this.index = index;
this.fence = fence;
this.origin = origin;
this.bound = bound;
}
public RandomIntsSpliterator trySplit() {
long i = index, m = (i + fence) >>> 1;
return (m<=i) ? null : new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound);
}
public long estimateSize() {
return fence - index;
}
public int characteristics() {
return (Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE);
}
public boolean tryAdvance(IntConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
consumer.accept(rng.internalNextInt(origin, bound));
index = i + 1;
return true;
}
return false;
}
public void forEachRemaining(IntConsumer consumer) {
if(consumer == null)
throw new NullPointerException();
long i = index, f = fence;
if(i<f) {
index = f;
SplittableRandom r = rng;
int o = origin, b = bound;
do {
consumer.accept(r.internalNextInt(o, b));
} while(++i<f);
}
}
}
/**
* Spliterator for long streams.
*/
// 可以随机生成long元素的流
private static final class RandomLongsSpliterator implements Spliterator.OfLong {
final SplittableRandom rng;
// 随机数数量:fence-index
long index;