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