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