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>192</sup>.  Class {@link L64X128StarStarRandom} 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 L64X128StarStarRandom}
43  * objects or streams of such objects.
44  *
45  * <p>The {@link L64X128StarStarRandom} 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 L64X128StarStarRandom}
49  * has 192 bits of state plus one 64-bit instance-specific parameter.
50  *
51  * <p>If two instances of {@link L64X128StarStarRandom} 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 L64X128StarStarRandom} 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(someL64X128StarStarRandom.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 L64X128StarStarRandom} 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 = "L64X128StarStarRandom",
80         group = "LXM",
81         i = 128, j = 1, k = 64,
82         equidistribution = 2
83 )
84 public final class L64X128StarStarRandom extends AbstractSplittableWithBrineGenerator {
85 
86     /*
87      * Implementation Overview.
88      *
89      * The split operation uses the current generator to choose four new 64-bit
90      * long values that are then used to initialize the parameter `a` and the
91      * state variables `s`, `x0`, and `x1` for a newly constructed generator.
92      *
93      * With extremely high probability, no two generators so chosen
94      * will have the same `a` parameter, and testing has indicated
95      * that the values generated by two instances of {@link L64X128StarStarRandom}
96      * will be (approximately) independent if have different values for `a`.
97      *
98      * The default (no-argument) constructor, in essence, uses
99      * "defaultGen" to generate four new 64-bit values for the same
100      * purpose.  Multiple generators created in this way will certainly
101      * differ in their `a` parameters.  The defaultGen state must be accessed
102      * in a thread-safe manner, so we use an AtomicLong to represent
103      * this state.  To bootstrap the defaultGen, we start off using a
104      * seed based on current time unless the
105      * java.util.secureRandomSeed property is set. This serves as a
106      * slimmed-down (and insecure) variant of SecureRandom that also
107      * avoids stalls that may occur when using /dev/random.
108      *
109      * File organization: First static fields, then instance
110      * fields, then constructors, then instance methods.
111      */
112 
113     /* ---------------- static fields ---------------- */
114 
115     /**
116      * The seed generator for default constructors.
117      */
118     private static final AtomicLong defaultGen = new AtomicLong(RandomSupport.initialSeed());
119 
120     /*
121      * Multiplier used in the LCG portion of the algorithm.
122      * Chosen based on research by Sebastiano Vigna and Guy Steele (2019).
123      * The spectral scores for dimensions 2 through 8 for the multiplier 0xd1342543de82ef95
124      * are [0.958602, 0.937479, 0.870757, 0.822326, 0.820405, 0.813065, 0.760215].
125      */
126 
127     private static final long M = 0xd1342543de82ef95L;
128 
129     /* ---------------- instance fields ---------------- */
130 
131     /**
132      * The parameter that is used as an additive constant for the LCG.
133      * Must be odd.
134      */
135     private final long a;
136 
137     /**
138      * The per-instance state: s for the LCG; x0 and x1 for the XBG.
139      * At least one of x0 and x1 must be nonzero.
140      */
141     private long s, x0, x1;
142 
143     /* ---------------- constructors ---------------- */
144 
145     /**
146      * Basic constructor that initializes all fields from parameters.
147      * It then adjusts the field values if necessary to ensure that
148      * all constraints on the values of fields are met.
149      *
150      * @param a additive parameter for the LCG
151      * @param s initial state for the LCG
152      * @param x0 first word of the initial state for the XBG
153      * @param x1 second word of the initial state for the XBG
154      */
L64X128StarStarRandom(long a, long s, long x0, long x1)155     public L64X128StarStarRandom(long a, long s, long x0, long x1) {
156         // Force a to be odd.
157         this.a = a | 1;
158         this.s = s;
159         this.x0 = x0;
160         this.x1 = x1;
161         // If x0 and x1 are both zero, we must choose nonzero values.
162         if ((x0 | x1) == 0) {
163        long v = s;
164             // At least one of the two values generated here will be nonzero.
165             this.x0 = RandomSupport.mixStafford13(v += RandomSupport.GOLDEN_RATIO_64);
166             this.x1 = RandomSupport.mixStafford13(v + RandomSupport.GOLDEN_RATIO_64);
167         }
168     }
169 
170     /**
171      * Creates a new instance of {@link L64X128StarStarRandom} using the
172      * specified {@code long} value as the initial seed. Instances of
173      * {@link L64X128StarStarRandom} created with the same seed in the same
174      * program generate identical sequences of values.
175      *
176      * @param seed the initial seed
177      */
L64X128StarStarRandom(long seed)178     public L64X128StarStarRandom(long seed) {
179         // Using a value with irregularly spaced 1-bits to xor the seed
180         // argument tends to improve "pedestrian" seeds such as 0 or
181         // other small integers.  We may as well use SILVER_RATIO_64.
182         //
183         // The seed is hashed by mixMurmur64 to produce the `a` parameter.
184         // The seed is hashed by mixStafford13 to produce the initial `x0`,
185         // which will then be used to produce the first generated value.
186         // Then x1 is filled in as if by a SplitMix PRNG with
187         // GOLDEN_RATIO_64 as the gamma value and mixStafford13 as the mixer.
188         this(RandomSupport.mixMurmur64(seed ^= RandomSupport.SILVER_RATIO_64),
189              1,
190              RandomSupport.mixStafford13(seed),
191              RandomSupport.mixStafford13(seed + RandomSupport.GOLDEN_RATIO_64));
192     }
193 
194     /**
195      * Creates a new instance of {@link L64X128StarStarRandom} that is likely to
196      * generate sequences of values that are statistically independent
197      * of those of any other instances in the current program execution,
198      * but may, and typically does, vary across program invocations.
199      */
L64X128StarStarRandom()200     public L64X128StarStarRandom() {
201         // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
202         this(defaultGen.getAndAdd(RandomSupport.GOLDEN_RATIO_64));
203     }
204 
205     /**
206      * Creates a new instance of {@link L64X128StarStarRandom} using the specified array of
207      * initial seed bytes. Instances of {@link L64X128StarStarRandom} created with the same
208      * seed array in the same program execution generate identical sequences of values.
209      *
210      * @param seed the initial seed
211      */
L64X128StarStarRandom(byte[] seed)212     public L64X128StarStarRandom(byte[] seed) {
213         // Convert the seed to 4 long values, of which the last 2 are not all zero.
214         long[] data = RandomSupport.convertSeedBytesToLongs(seed, 4, 2);
215         long a = data[0], s = data[1], x0 = data[2], x1 = data[3];
216         // Force a to be odd.
217         this.a = a | 1;
218         this.s = s;
219         this.x0 = x0;
220         this.x1 = x1;
221     }
222 
223     /* ---------------- public methods ---------------- */
224 
225     @Override
split(SplittableGenerator source, long brine)226     public SplittableGenerator split(SplittableGenerator source, long brine) {
227        // Pick a new instance "at random", but use the brine for `a`.
228         return new L64X128StarStarRandom(brine << 1, source.nextLong(),
229                     source.nextLong(), source.nextLong());
230     }
231 
232     @Override
nextLong()233     public long nextLong() {
234        // Compute the result based on current state information
235        // (this allows the computation to be overlapped with state update).
236         final long result = Long.rotateLeft((s + x0) * 5, 7) * 9;  // "starstar" scrambler
237 
238        // Update the LCG subgenerator
239         s = M * s + a;
240 
241        // Update the XBG subgenerator
242         long q0 = x0, q1 = x1;
243         {   // xoroshiro128v1_0
244             q1 ^= q0;
245             q0 = Long.rotateLeft(q0, 24);
246             q0 = q0 ^ q1 ^ (q1 << 16);
247             q1 = Long.rotateLeft(q1, 37);
248         }
249         x0 = q0; x1 = q1;
250 
251         return result;
252     }
253 
254 }
255