RandomRegistry.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.1.0).
003  * Copyright (c) 2007-2020 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019  */
020 package io.jenetics.util;
021 
022 import static java.util.Objects.requireNonNull;
023 
024 import java.util.Random;
025 import java.util.concurrent.ThreadLocalRandom;
026 import java.util.function.Consumer;
027 import java.util.function.Function;
028 import java.util.function.Supplier;
029 
030 /**
031  * This class holds the {@link Random} engine used for the GA. The
032  * {@code RandomRegistry} is thread safe. The registry is initialized with the
033  {@link ThreadLocalRandom} PRNG, which has a much better performance behavior
034  * than an instance of the {@code Random} class. Alternatively, you can
035  * initialize the registry with one of the PRNG, which are being part of the
036  * library.
037  <p>
038  *
039  <b>Setup of a <i>global</i> PRNG</b>
040  *
041  <pre>{@code
042  * public class GA {
043  *     public static void main(final String[] args) {
044  *         // Initialize the registry with a ThreadLocal instance of the PRGN.
045  *         // This is the preferred way setting a new PRGN.
046  *         RandomRegistry.random(new LCG64ShiftRandom.ThreadLocal());
047  *
048  *         // Using a thread safe variant of the PRGN. Leads to slower PRN
049  *         // generation, but gives you the possibility to set a PRNG seed.
050  *         RandomRegistry.random(new LCG64ShiftRandom.ThreadSafe(1234));
051  *
052  *         ...
053  *         final EvolutionResult<DoubleGene, Double> result = stream
054  *             .limit(100)
055  *             .collect(toBestEvolutionResult());
056  *     }
057  * }
058  * }</pre>
059  <p>
060  *
061  <b>Setup of a <i>local</i> PRNG</b><br>
062  *
063  * You can temporarily (and locally) change the implementation of the PRNG. E.g.
064  * for initialize the engine stream with the same initial population.
065  *
066  <pre>{@code
067  * public class GA {
068  *     public static void main(final String[] args) {
069  *         // Create a reproducible list of genotypes.
070  *         final List<Genotype<DoubleGene>> genotypes =
071  *             with(new LCG64ShiftRandom(123), r ->
072  *                 Genotype.of(DoubleChromosome.of(0, 10)).instances()
073  *                     .limit(50)
074  *                     .collect(toList())
075  *             );
076  *
077  *         final Engine<DoubleGene, Double> engine = ...;
078  *         final EvolutionResult<DoubleGene, Double> result = engine
079  *              // Initialize the evolution stream with the given genotypes.
080  *             .stream(genotypes)
081  *             .limit(100)
082  *             .collect(toBestEvolutionResult());
083  *     }
084  * }
085  * }</pre>
086  <p>
087  *
088  @see Random
089  @see ThreadLocalRandom
090  *
091  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
092  @since 1.0
093  @version 3.0
094  */
095 public final class RandomRegistry {
096     private RandomRegistry() {}
097 
098     private static final Context<Supplier<Random>> CONTEXT =
099         new Context<>(ThreadLocalRandom::current);
100 
101     /**
102      * Return the global {@link Random} object.
103      *
104      @return the global {@link Random} object.
105      */
106     public static Random random() {
107         return CONTEXT.get().get();
108     }
109 
110     /**
111      * Set the new global {@link Random} object for the GA. The given
112      {@link Random} <b>must</b> be thread safe, which is the case for the
113      * default Java {@code Random} implementation.
114      <p>
115      * Setting a <i>thread-local</i> random object leads, in general, to a faster
116      * PRN generation, because the given {@code Random} engine don't have to be
117      * thread-safe.
118      *
119      @see #random(ThreadLocal)
120      *
121      @param random the new global {@link Random} object for the GA.
122      @throws NullPointerException if the {@code random} object is {@code null}.
123      */
124     public static void random(final Random random) {
125         requireNonNull(random, "Random must not be null.");
126         CONTEXT.set(() -> random);
127     }
128 
129     /**
130      * Set the new global {@link Random} object for the GA. The given
131      {@link Random} don't have be thread safe, because the given
132      {@link ThreadLocal} wrapper guarantees thread safety. Setting a
133      <i>thread-local</i> random object leads, in general, to a faster
134      * PRN generation, when using a non-blocking PRNG. This is the preferred
135      * way for changing the PRNG.
136      *
137      @param random the thread-local random engine to use.
138      @throws NullPointerException if the {@code random} object is {@code null}.
139      */
140     public static void random(final ThreadLocal<? extends Random> random) {
141         requireNonNull(random, "Random must not be null.");
142         CONTEXT.set(random::get);
143     }
144 
145     /**
146      * Set the random object to it's default value. The <i>default</i> used PRNG
147      * is the {@link ThreadLocalRandom} PRNG.
148      */
149     public static void reset() {
150         CONTEXT.reset();
151     }
152 
153     /**
154      * Executes the consumer code using the given {@code random} engine.
155      *
156      <pre>{@code
157      * final MSeq<Integer> seq = ...
158      * using(new Random(123), r -> {
159      *     seq.shuffle();
160      * });
161      * }</pre>
162      *
163      * The example above shuffles the given integer {@code seq} <i>using</i> the
164      * given {@code Random(123)} engine.
165      *
166      @since 3.0
167      *
168      @param random the PRNG used within the consumer
169      @param consumer the consumer which is executed with the <i>scope</i> of
170      *        the given {@code random} engine.
171      @param <R> the type of the random engine
172      @throws NullPointerException if one of the arguments is {@code null}
173      */
174     public static <R extends Random> void using(
175         final R random,
176         final Consumer<? super R> consumer
177     ) {
178         CONTEXT.with(() -> random, r -> {
179             consumer.accept(random);
180             return null;
181         });
182     }
183 
184     /**
185      * Executes the consumer code using the given {@code random} engine.
186      *
187      <pre>{@code
188      * final MSeq<Integer> seq = ...
189      * using(new LCG64ShiftRandom.ThreadLocal(), r -> {
190      *     seq.shuffle();
191      * });
192      * }</pre>
193      *
194      * The example above shuffles the given integer {@code seq} <i>using</i> the
195      * given {@code LCG64ShiftRandom.ThreadLocal()} engine.
196      *
197      @since 3.0
198      *
199      @param random the PRNG used within the consumer
200      @param consumer the consumer which is executed with the <i>scope</i> of
201      *        the given {@code random} engine.
202      @param <R> the type of the random engine
203      @throws NullPointerException if one of the arguments is {@code null}
204      */
205     public static <R extends Random> void using(
206         final ThreadLocal<R> random,
207         final Consumer<? super R> consumer
208     ) {
209         CONTEXT.with(random::get, r -> {
210             consumer.accept(random.get());
211             return null;
212         });
213     }
214 
215     /**
216      * Opens a new {@code Scope} with the given random engine and executes the
217      * given function within it. The following example shows how to create a
218      * reproducible list of genotypes:
219      <pre>{@code
220      * final List<Genotype<DoubleGene>> genotypes =
221      *     with(new LCG64ShiftRandom(123), r ->
222      *         Genotype.of(DoubleChromosome.of(0, 10)).instances()
223      *            .limit(50)
224      *            .collect(toList())
225      *     );
226      * }</pre>
227      *
228      @since 3.0
229      *
230      @param <R> the type of the random engine
231      @param <T> the function return type
232      @param random the PRNG used for the opened scope
233      @param function the function to apply within the random scope
234      @return the object returned by the given function
235      @throws NullPointerException if one of the arguments is {@code null}
236      */
237     public static <R extends Random, T> T with(
238         final R random,
239         final Function<? super R, ? extends T> function
240     ) {
241         return CONTEXT.with(() -> random, s -> function.apply(random));
242     }
243 
244     /**
245      * Opens a new {@code Scope} with the given random engine and executes the
246      * given function within it. The following example shows how to create a
247      * reproducible list of genotypes:
248      <pre>{@code
249      * final List<Genotype<DoubleGene>> genotypes =
250      *     with(new LCG64ShiftRandom.ThreadLocal(), random ->
251      *         Genotype.of(DoubleChromosome.of(0, 10)).instances()
252      *            .limit(50)
253      *            .collect(toList())
254      *     );
255      * }</pre>
256      *
257      @since 3.0
258      *
259      @param <R> the type of the random engine
260      @param <T> the function return type
261      @param random the PRNG used for the opened scope
262      @param function the function to apply within the random scope
263      @return the object returned by the given function
264      @throws NullPointerException if one of the arguments is {@code null}.
265      */
266     public static <R extends Random, T> T with(
267         final ThreadLocal<R> random,
268         final Function<? super R, ? extends T> function
269     ) {
270         return CONTEXT.with(random::get, s -> function.apply(random.get()));
271     }
272 
273 }