1 /*
2  * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
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 
26 package jdk.random;
27 
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.random.RandomGenerator;
30 import jdk.internal.util.random.RandomSupport;
31 import jdk.internal.util.random.RandomSupport.AbstractSplittableWithBrineGenerator;
32 import jdk.internal.util.random.RandomSupport.RandomGeneratorProperties;
33 
34 /**
35  * A "splittable" pseudorandom number generator (PRNG) whose period
36  * is roughly 2<sup>96</sup>.  Class {@link L32X64MixRandom} implements
37  * interfaces {@link RandomGenerator} and {@link SplittableGenerator},
38  * and therefore supports methods for producing pseudorandomly chosen
39  * values of type {@code int}, {@code long}, {@code float}, {@code double},
40  * and {@code boolean} (and for producing streams of pseudorandomly chosen
41  * numbers of type {@code int}, {@code long}, and {@code double}),
42  * as well as methods for creating new split-off {@link L32X64MixRandom}
43  * objects or streams of such objects.
44  *
45  * <p>The {@link L32X64MixRandom} algorithm is a specific member of
46  * the LXM family of algorithms for pseudorandom number generators;
47  * for more information, see the documentation for package
48  * {@link jdk.random}.  Each instance of {@link L32X64MixRandom}
49  * has 96 bits of state plus one 32-bit instance-specific parameter.
50  *
51  * <p>If two instances of {@link L32X64MixRandom} are created with
52  * the same seed within the same program execution, and the same
53  * sequence of method calls is made for each, they will generate and
54  * return identical sequences of values.
55  *
56  * <p>As with {@link java.util.SplittableRandom}, instances of
57  * {@link L32X64MixRandom} are <em>not</em> thread-safe.  They are
58  * designed to be split, not shared, across threads (see the {@link #split}
59  * method). For example, a {@link java.util.concurrent.ForkJoinTask}
60  * fork/join-style computation using random numbers might include a
61  * construction of the form
62  * {@code new Subtask(someL32X64MixRandom.split()).fork()}.
63  *
64  * <p>This class provides additional methods for generating random
65  * streams, that employ the above techniques when used in
66  * {@code stream.parallel()} mode.
67  *
68  * <p>Instances of {@link L32X64MixRandom} are not cryptographically
69  * secure.  Consider instead using {@link java.security.SecureRandom}
70  * in security-sensitive applications. Additionally,
71  * default-constructed instances do not use a cryptographically random
72  * seed unless the {@linkplain System#getProperty system property}
73  * {@code java.util.secureRandomSeed} is set to {@code true}.
74  *
75  * @since   17
76  *
77  */
78 @RandomGeneratorProperties(
79         name = "L32X64MixRandom",
80         group = "LXM",
81         i = 64, j = 1, k = 32,
82         equidistribution = 1
83 )
84 public final class L32X64MixRandom extends AbstractSplittableWithBrineGenerator {
85     /*
86      * Implementation Overview.
87      *
88      * The split operation uses the current generator to choose four new 32-bit
89      * int values that are then used to initialize the parameter `a` and the
90      * state variables `s`, `x0`, and `x1` for a newly constructed generator.
91      *
92      * With high probability, no two generators so chosen will have the same
93      * `a` parameter, and testing has indicated that the values generated by
94      * two instances of {@link L32X64MixRandom} will be (approximately)
95      * independent if the two instances have different values for `a`.
96      *
97      * The default (no-argument) constructor, in essence, uses
98      * "defaultGen" to generate four new 32-bit values for the same
99      * purpose.  Multiple generators created in this way will certainly
100      * differ in their `a` parameters.  The defaultGen state must be accessed
101      * in a thread-safe manner, so we use an AtomicLong to represent
102      * this state.  To bootstrap the defaultGen, we start off using a
103      * seed based on current time unless the
104      * java.util.secureRandomSeed property is set. This serves as a
105      * slimmed-down (and insecure) variant of SecureRandom that also
106      * avoids stalls that may occur when using /dev/random.
107      *
108      * File organization: First static fields, then instance
109      * fields, then constructors, then instance methods.
110      */
111 
112     /* ---------------- static fields ---------------- */
113 
114     /**
115      * The seed generator for default constructors.
116      */
117     private static final AtomicLong defaultGen = new AtomicLong(RandomSupport.initialSeed());
118 
119     /*
120      * Multiplier used in the LCG portion of the algorithm.
121      * Chosen based on research by Sebastiano Vigna and Guy Steele (2019).
122      * The spectral scores for dimensions 2 through 8 for the multiplier 0xadb4a92d
123      * are [0.975884, 0.936244, 0.755793, 0.877642, 0.751300, 0.789333, 0.728869].
124      */
125 
126     private static final int M = 0xadb4a92d;
127 
128     /* ---------------- instance fields ---------------- */
129 
130     /**
131      * The parameter that is used as an additive constant for the LCG.
132      * Must be odd.
133      */
134     private final int a;
135 
136     /**
137      * The per-instance state: s for the LCG; x0 and x1 for the XBG.
138      * At least one of x0 and x1 must be nonzero.
139      */
140     private int s, x0, x1;
141 
142     /* ---------------- constructors ---------------- */
143 
144     /**
145      * Basic constructor that initializes all fields from parameters.
146      * It then adjusts the field values if necessary to ensure that
147      * all constraints on the values of fields are met.
148      *
149      * @param a additive parameter for the LCG
150      * @param s initial state for the LCG
151      * @param x0 first word of the initial state for the XBG
152      * @param x1 second word of the initial state for the XBG
153      */
L32X64MixRandom(int a, int s, int x0, int x1)154     public L32X64MixRandom(int a, int s, int x0, int x1) {
155         // Force a to be odd.
156         this.a = a | 1;
157         this.s = s;
158         this.x0 = x0;
159         this.x1 = x1;
160         // If x0 and x1 are both zero, we must choose nonzero values.
161         if ((x0 | x1) == 0) {
162        int v = s;
163             // At least one of the two values generated here will be nonzero.
164             this.x0 = RandomSupport.mixMurmur32(v += RandomSupport.GOLDEN_RATIO_32);
165             this.x1 = RandomSupport.mixMurmur32(v + RandomSupport.GOLDEN_RATIO_32);
166         }
167     }
168 
169     /**
170      * Creates a new instance of {@link L32X64MixRandom} using the
171      * specified {@code long} value as the initial seed. Instances of
172      * {@link L32X64MixRandom} created with the same seed in the same
173      * program generate identical sequences of values.
174      *
175      * @param seed the initial seed
176      */
L32X64MixRandom(long seed)177     public L32X64MixRandom(long seed) {
178         // Using a value with irregularly spaced 1-bits to xor the seed
179         // argument tends to improve "pedestrian" seeds such as 0 or
180         // other small integers.  We may as well use SILVER_RATIO_64.
181         //
182         // The high half of the seed is hashed by mixMurmur32 to produce the `a` parameter.
183         // The low half of the seed is hashed by mixLea32 to produce the initial `x0`,
184         // which will then be used to produce the first generated value.
185         // Then x1 is filled in as if by a SplitMix PRNG with
186         // GOLDEN_RATIO_32 as the gamma value and mixLea32 as the mixer.
187         this(RandomSupport.mixMurmur32((int)((seed ^= RandomSupport.SILVER_RATIO_64) >>> 32)),
188              1,
189              RandomSupport.mixLea32((int)(seed)),
190              RandomSupport.mixLea32((int)(seed) + RandomSupport.GOLDEN_RATIO_32));
191     }
192 
193     /**
194      * Creates a new instance of {@link L32X64MixRandom} that is likely to
195      * generate sequences of values that are statistically independent
196      * of those of any other instances in the current program execution,
197      * but may, and typically does, vary across program invocations.
198      */
L32X64MixRandom()199     public L32X64MixRandom() {
200         // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
201         this(defaultGen.getAndAdd(RandomSupport.GOLDEN_RATIO_64));
202     }
203 
204     /**
205      * Creates a new instance of {@link L32X64MixRandom} using the specified array of
206      * initial seed bytes. Instances of {@link L32X64MixRandom} created with the same
207      * seed array in the same program execution generate identical sequences of values.
208      *
209      * @param seed the initial seed
210      */
L32X64MixRandom(byte[] seed)211     public L32X64MixRandom(byte[] seed) {
212         // Convert the seed to 4 int values, of which the last 2 are not all zero.
213         int[] data = RandomSupport.convertSeedBytesToInts(seed, 4, 2);
214         int a = data[0], s = data[1], x0 = data[2], x1 = data[3];
215         // Force a to be odd.
216         this.a = a | 1;
217         this.s = s;
218         this.x0 = x0;
219         this.x1 = x1;
220     }
221 
222     /* ---------------- public methods ---------------- */
223 
224     @Override
split(SplittableGenerator source, long brine)225     public SplittableGenerator split(SplittableGenerator source, long brine) {
226        // Pick a new instance "at random", but use (the low 31 bits of) the brine for `a`.
227         return new L32X64MixRandom((int)brine << 1, source.nextInt(),
228                    source.nextInt(), source.nextInt());
229     }
230 
231     @Override
nextInt()232     public int nextInt() {
233        // Compute the result based on current state information
234        // (this allows the computation to be overlapped with state update).
235         final int result = RandomSupport.mixLea32(s + x0);
236 
237        // Update the LCG subgenerator
238         s = M * s + a;
239 
240        // Update the XBG subgenerator
241         int q0 = x0, q1 = x1;
242         {   // xoroshiro64
243             q1 ^= q0;
244             q0 = Integer.rotateLeft(q0, 26);
245             q0 = q0 ^ q1 ^ (q1 << 9);
246             q1 = Integer.rotateLeft(q1, 13);
247         }
248         x0 = q0; x1 = q1;
249 
250         return result;
251     }
252 
253     @Override
nextLong()254     public long nextLong() {
255         return ((long)nextInt() << 32) ^ (long)nextInt();
256     }
257 
258 }
259