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