author | briangoetz |
Tue, 04 Jun 2019 13:07:35 -0400 | |
branch | JDK-8193209-branch |
changeset 57388 | b1e6bc96af3d |
parent 52957 | c7c285b0b640 |
child 57437 | f02ffcb61dce |
permissions | -rw-r--r-- |
19592 | 1 |
/* |
57388 | 2 |
* Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. |
19592 | 3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Oracle designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Oracle in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
22 |
* or visit www.oracle.com if you need additional information or have any |
|
23 |
* questions. |
|
24 |
*/ |
|
25 |
package java.util; |
|
26 |
||
57388 | 27 |
import java.math.BigInteger; |
19592 | 28 |
import java.util.concurrent.atomic.AtomicLong; |
29 |
||
30 |
/** |
|
31 |
* A generator of uniform pseudorandom values applicable for use in |
|
32 |
* (among other contexts) isolated parallel computations that may |
|
33 |
* generate subtasks. Class {@code SplittableRandom} supports methods for |
|
34 |
* producing pseudorandom numbers of type {@code int}, {@code long}, |
|
35 |
* and {@code double} with similar usages as for class |
|
36 |
* {@link java.util.Random} but differs in the following ways: |
|
37 |
* |
|
38 |
* <ul> |
|
39 |
* |
|
40 |
* <li>Series of generated values pass the DieHarder suite testing |
|
41 |
* independence and uniformity properties of random number generators. |
|
42 |
* (Most recently validated with <a |
|
43 |
* href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version |
|
44 |
* 3.31.1</a>.) These tests validate only the methods for certain |
|
45 |
* types and ranges, but similar properties are expected to hold, at |
|
46 |
* least approximately, for others as well. The <em>period</em> |
|
47 |
* (length of any series of generated values before it repeats) is at |
|
57388 | 48 |
* least 2<sup>64</sup>. </li> |
19592 | 49 |
* |
57388 | 50 |
* <li> Method {@link #split} constructs and returns a new |
19592 | 51 |
* SplittableRandom instance that shares no mutable state with the |
52 |
* current instance. However, with very high probability, the |
|
53 |
* values collectively generated by the two objects have the same |
|
54 |
* statistical properties as if the same quantity of values were |
|
55 |
* generated by a single thread using a single {@code |
|
57388 | 56 |
* SplittableRandom} object. </li> |
19592 | 57 |
* |
58 |
* <li>Instances of SplittableRandom are <em>not</em> thread-safe. |
|
59 |
* They are designed to be split, not shared, across threads. For |
|
60 |
* example, a {@link java.util.concurrent.ForkJoinTask |
|
61 |
* fork/join-style} computation using random numbers might include a |
|
62 |
* construction of the form {@code new |
|
63 |
* Subtask(aSplittableRandom.split()).fork()}. |
|
64 |
* |
|
65 |
* <li>This class provides additional methods for generating random |
|
66 |
* streams, that employ the above techniques when used in {@code |
|
57388 | 67 |
* stream.parallel()} mode.</li> |
19592 | 68 |
* |
69 |
* </ul> |
|
70 |
* |
|
71 |
* <p>Instances of {@code SplittableRandom} are not cryptographically |
|
72 |
* secure. Consider instead using {@link java.security.SecureRandom} |
|
73 |
* in security-sensitive applications. Additionally, |
|
74 |
* default-constructed instances do not use a cryptographically random |
|
75 |
* seed unless the {@linkplain System#getProperty system property} |
|
57388 | 76 |
* {@code java.util.secureRandomSeed} is set to {@code true}. |
19592 | 77 |
* |
78 |
* @author Guy Steele |
|
79 |
* @author Doug Lea |
|
80 |
* @since 1.8 |
|
81 |
*/ |
|
57388 | 82 |
public final class SplittableRandom extends AbstractSplittableRng { |
19592 | 83 |
|
84 |
/* |
|
85 |
* Implementation Overview. |
|
86 |
* |
|
87 |
* This algorithm was inspired by the "DotMix" algorithm by |
|
88 |
* Leiserson, Schardl, and Sukha "Deterministic Parallel |
|
89 |
* Random-Number Generation for Dynamic-Multithreading Platforms", |
|
90 |
* PPoPP 2012, as well as those in "Parallel random numbers: as |
|
91 |
* easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It |
|
92 |
* differs mainly in simplifying and cheapening operations. |
|
93 |
* |
|
94 |
* The primary update step (method nextSeed()) is to add a |
|
95 |
* constant ("gamma") to the current (64 bit) seed, forming a |
|
96 |
* simple sequence. The seed and the gamma values for any two |
|
97 |
* SplittableRandom instances are highly likely to be different. |
|
98 |
* |
|
99 |
* Methods nextLong, nextInt, and derivatives do not return the |
|
100 |
* sequence (seed) values, but instead a hash-like bit-mix of |
|
101 |
* their bits, producing more independently distributed sequences. |
|
20540 | 102 |
* For nextLong, the mix64 function is based on David Stafford's |
103 |
* (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html) |
|
104 |
* "Mix13" variant of the "64-bit finalizer" function in Austin |
|
105 |
* Appleby's MurmurHash3 algorithm (see |
|
106 |
* http://code.google.com/p/smhasher/wiki/MurmurHash3). The mix32 |
|
107 |
* function is based on Stafford's Mix04 mix function, but returns |
|
108 |
* the upper 32 bits cast as int. |
|
19592 | 109 |
* |
110 |
* The split operation uses the current generator to form the seed |
|
111 |
* and gamma for another SplittableRandom. To conservatively |
|
112 |
* avoid potential correlations between seed and value generation, |
|
20540 | 113 |
* gamma selection (method mixGamma) uses different |
114 |
* (Murmurhash3's) mix constants. To avoid potential weaknesses |
|
115 |
* in bit-mixing transformations, we restrict gammas to odd values |
|
116 |
* with at least 24 0-1 or 1-0 bit transitions. Rather than |
|
117 |
* rejecting candidates with too few or too many bits set, method |
|
118 |
* mixGamma flips some bits (which has the effect of mapping at |
|
119 |
* most 4 to any given gamma value). This reduces the effective |
|
120 |
* set of 64bit odd gamma values by about 2%, and serves as an |
|
19592 | 121 |
* automated screening for sequence constant selection that is |
122 |
* left as an empirical decision in some other hashing and crypto |
|
123 |
* algorithms. |
|
124 |
* |
|
125 |
* The resulting generator thus transforms a sequence in which |
|
126 |
* (typically) many bits change on each step, with an inexpensive |
|
127 |
* mixer with good (but less than cryptographically secure) |
|
128 |
* avalanching. |
|
129 |
* |
|
130 |
* The default (no-argument) constructor, in essence, invokes |
|
20540 | 131 |
* split() for a common "defaultGen" SplittableRandom. Unlike |
132 |
* other cases, this split must be performed in a thread-safe |
|
133 |
* manner, so we use an AtomicLong to represent the seed rather |
|
134 |
* than use an explicit SplittableRandom. To bootstrap the |
|
27797
7734f206f415
8066397: Remove network-related seed initialization code in ThreadLocal/SplittableRandom
psandoz
parents:
25859
diff
changeset
|
135 |
* defaultGen, we start off using a seed based on current time |
7734f206f415
8066397: Remove network-related seed initialization code in ThreadLocal/SplittableRandom
psandoz
parents:
25859
diff
changeset
|
136 |
* unless the java.util.secureRandomSeed property is set. This |
7734f206f415
8066397: Remove network-related seed initialization code in ThreadLocal/SplittableRandom
psandoz
parents:
25859
diff
changeset
|
137 |
* serves as a slimmed-down (and insecure) variant of SecureRandom |
7734f206f415
8066397: Remove network-related seed initialization code in ThreadLocal/SplittableRandom
psandoz
parents:
25859
diff
changeset
|
138 |
* that also avoids stalls that may occur when using /dev/random. |
19592 | 139 |
* |
140 |
* It is a relatively simple matter to apply the basic design here |
|
141 |
* to use 128 bit seeds. However, emulating 128bit arithmetic and |
|
142 |
* carrying around twice the state add more overhead than appears |
|
143 |
* warranted for current usages. |
|
144 |
* |
|
145 |
* File organization: First the non-public methods that constitute |
|
146 |
* the main algorithm, then the main public methods, followed by |
|
147 |
* some custom spliterator classes needed for stream methods. |
|
148 |
*/ |
|
149 |
||
150 |
/** |
|
20540 | 151 |
* The golden ratio scaled to 64bits, used as the initial gamma |
152 |
* value for (unsplit) SplittableRandoms. |
|
19592 | 153 |
*/ |
20540 | 154 |
private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L; |
19592 | 155 |
|
156 |
/** |
|
157 |
* The seed. Updated only via method nextSeed. |
|
158 |
*/ |
|
159 |
private long seed; |
|
160 |
||
161 |
/** |
|
162 |
* The step value. |
|
163 |
*/ |
|
164 |
private final long gamma; |
|
165 |
||
166 |
/** |
|
167 |
* Internal constructor used by all others except default constructor. |
|
168 |
*/ |
|
169 |
private SplittableRandom(long seed, long gamma) { |
|
170 |
this.seed = seed; |
|
171 |
this.gamma = gamma; |
|
172 |
} |
|
173 |
||
174 |
/** |
|
20540 | 175 |
* Computes Stafford variant 13 of 64bit mix function. |
57388 | 176 |
* http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html |
19592 | 177 |
*/ |
178 |
private static long mix64(long z) { |
|
20540 | 179 |
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; |
180 |
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL; |
|
181 |
return z ^ (z >>> 31); |
|
19592 | 182 |
} |
183 |
||
184 |
/** |
|
20540 | 185 |
* Returns the 32 high bits of Stafford variant 4 mix64 function as int. |
57388 | 186 |
* http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html |
19592 | 187 |
*/ |
188 |
private static int mix32(long z) { |
|
20540 | 189 |
z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L; |
190 |
return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32); |
|
19592 | 191 |
} |
192 |
||
193 |
/** |
|
194 |
* Returns the gamma value to use for a new split instance. |
|
57388 | 195 |
* Uses the 64bit mix function from MurmurHash3. |
196 |
* https://github.com/aappleby/smhasher/wiki/MurmurHash3 |
|
19592 | 197 |
*/ |
20540 | 198 |
private static long mixGamma(long z) { |
199 |
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; // MurmurHash3 mix constants |
|
200 |
z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L; |
|
201 |
z = (z ^ (z >>> 33)) | 1L; // force to be odd |
|
202 |
int n = Long.bitCount(z ^ (z >>> 1)); // ensure enough transitions |
|
203 |
return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z; |
|
19592 | 204 |
} |
205 |
||
206 |
/** |
|
207 |
* Adds gamma to seed. |
|
208 |
*/ |
|
209 |
private long nextSeed() { |
|
210 |
return seed += gamma; |
|
211 |
} |
|
212 |
||
213 |
/** |
|
214 |
* The seed generator for default constructors. |
|
215 |
*/ |
|
57388 | 216 |
private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed()); |
217 |
||
19592 | 218 |
/* ---------------- public methods ---------------- */ |
219 |
||
220 |
/** |
|
221 |
* Creates a new SplittableRandom instance using the specified |
|
222 |
* initial seed. SplittableRandom instances created with the same |
|
223 |
* seed in the same program generate identical sequences of values. |
|
224 |
* |
|
225 |
* @param seed the initial seed |
|
226 |
*/ |
|
227 |
public SplittableRandom(long seed) { |
|
20540 | 228 |
this(seed, GOLDEN_GAMMA); |
19592 | 229 |
} |
230 |
||
231 |
/** |
|
232 |
* Creates a new SplittableRandom instance that is likely to |
|
233 |
* generate sequences of values that are statistically independent |
|
234 |
* of those of any other instances in the current program; and |
|
235 |
* may, and typically does, vary across program invocations. |
|
236 |
*/ |
|
20540 | 237 |
public SplittableRandom() { // emulate defaultGen.split() |
57388 | 238 |
long s = defaultGen.getAndAdd(2 * GOLDEN_GAMMA); |
20540 | 239 |
this.seed = mix64(s); |
240 |
this.gamma = mixGamma(s + GOLDEN_GAMMA); |
|
19592 | 241 |
} |
242 |
||
57388 | 243 |
// public SplittableRandom copy() { return new SplittableRandom(seed, gamma); } |
244 |
||
19592 | 245 |
/** |
246 |
* Constructs and returns a new SplittableRandom instance that |
|
247 |
* shares no mutable state with this instance. However, with very |
|
248 |
* high probability, the set of values collectively generated by |
|
249 |
* the two objects has the same statistical properties as if the |
|
250 |
* same quantity of values were generated by a single thread using |
|
251 |
* a single SplittableRandom object. Either or both of the two |
|
252 |
* objects may be further split using the {@code split()} method, |
|
253 |
* and the same expected statistical properties apply to the |
|
254 |
* entire set of generators constructed by such recursive |
|
255 |
* splitting. |
|
256 |
* |
|
257 |
* @return the new SplittableRandom instance |
|
258 |
*/ |
|
259 |
public SplittableRandom split() { |
|
20540 | 260 |
return new SplittableRandom(nextLong(), mixGamma(nextSeed())); |
19592 | 261 |
} |
262 |
||
57388 | 263 |
public SplittableRandom split(SplittableRng source) { |
264 |
return new SplittableRandom(source.nextLong(), mixGamma(source.nextLong())); |
|
47342 | 265 |
} |
266 |
||
267 |
/** |
|
19592 | 268 |
* Returns a pseudorandom {@code int} value. |
269 |
* |
|
270 |
* @return a pseudorandom {@code int} value |
|
271 |
*/ |
|
272 |
public int nextInt() { |
|
273 |
return mix32(nextSeed()); |
|
274 |
} |
|
275 |
||
276 |
/** |
|
277 |
* Returns a pseudorandom {@code long} value. |
|
278 |
* |
|
279 |
* @return a pseudorandom {@code long} value |
|
280 |
*/ |
|
281 |
public long nextLong() { |
|
282 |
return mix64(nextSeed()); |
|
283 |
} |
|
284 |
||
57388 | 285 |
static final BigInteger thePeriod = BigInteger.ONE.shiftLeft(64); // Period is 2**64 |
286 |
public BigInteger period() { return thePeriod; } |
|
19592 | 287 |
|
288 |
} |