001 /*
002 * Java Genetic Algorithm Library (jenetics-1.6.0).
003 * Copyright (c) 2007-2014 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@gmx.at)
019 */
020 package org.jenetics.util;
021
022 import static java.util.Objects.requireNonNull;
023
024 import java.util.Random;
025 import java.util.concurrent.ThreadLocalRandom;
026
027 import javolution.context.LocalContext;
028 import javolution.lang.Reference;
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 * [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.setRandom(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.setRandom(new LCG64ShiftRandom.ThreadSafe(1234));
051 *
052 * ...
053 * final GeneticAlgorithm<DoubleGene, Double> ga = ...
054 * ga.evolve(100);
055 * }
056 * }
057 * [/code]
058 * <p/>
059 *
060 * <b>Setup of a <i>local</i> PRNG</b><br/>
061 *
062 * Within a scoped context you can temporarily (and locally) change the
063 * implementation of the PRNG.
064 *
065 * [code]
066 * public class GA {
067 * public static void main(final String[] args) {
068 * ...
069 * final GeneticAlgorithm<DoubleGene, Double> ga = ...
070 * final LCG64ShiftRandom random = new LCG64ShiftRandom(1234);
071 *
072 * try (Scoped<Random> scope = RandomRegistry.scope(random)) {
073 * // Easy access the random engine of the opened scope.
074 * assert(scope.get() == random);
075 *
076 * // Only the 'setup' step uses the new PRGN.
077 * ga.setup();
078 * }
079 *
080 * ga.evolve(100);
081 * }
082 * }
083 * [/code]
084 * <p/>
085 *
086 * @see Random
087 * @see ThreadLocalRandom
088 * @see LCG64ShiftRandom
089 *
090 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
091 * @since 1.0
092 * @version 1.6 — <em>$Date: 2014-03-03 $</em>
093 */
094 public final class RandomRegistry extends StaticObject {
095 private RandomRegistry() {}
096
097 private static final Reference<Random> TLOCAL_REF = new Ref<Random>() {
098 @Override
099 public Random get() {
100 return ThreadLocalRandom.current();
101 }
102 };
103
104 private static final LocalContext.Reference<Reference<? extends Random>>
105 RANDOM = new LocalContext.Reference<Reference<? extends Random>>(TLOCAL_REF);
106
107 /**
108 * Return the global {@link Random} object.
109 *
110 * @return the global {@link Random} object.
111 */
112 public static Random getRandom() {
113 return RANDOM.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 RANDOM.set(new RRef(random));
132 }
133
134 /**
135 * Set the new global {@link Random} object for the GA. The given
136 * {@link Random} don't have be thread safe, because the given
137 * {@link ThreadLocal} wrapper guarantees thread safety. Setting a
138 * <i>thread-local</i> random object leads, in general, to a faster
139 * PRN generation, when using a non-blocking PRNG. This is the preferred
140 * way for changing the PRNG.
141 *
142 * @param random the thread-local random engine to use.
143 * @throws NullPointerException if the {@code random} object is {@code null}.
144 */
145 public static void setRandom(final ThreadLocal<? extends Random> random) {
146 RANDOM.set(new TLRRef<>(random));
147 }
148
149 /**
150 * Set the random object to it's default value. The <i>default</i> used PRNG
151 * is the {@link ThreadLocalRandom} PRNG.
152 */
153 public static void reset() {
154 RANDOM.set(TLOCAL_REF);
155 }
156
157 /**
158 * Opens a new {@code Scope} with the given random engine.
159 *
160 * @since 1.6
161 * @param random the PRNG used for the opened scope.
162 * @return the scope with the given random object.
163 */
164 public static <R extends Random> Scoped<R> scope(final R random) {
165 LocalContext.enter();
166 setRandom(random);
167 return new Scope<>(Thread.currentThread(), random);
168 }
169
170 /*
171 * Some helper Reference classes.
172 */
173
174 private static abstract class Ref<R> implements Reference<R> {
175 @Override public void set(final R random) {}
176 }
177
178 private final static class RRef extends Ref<Random> {
179 private final Random _random;
180 public RRef(final Random random) {
181 _random = requireNonNull(random, "Random");
182 }
183 @Override public final Random get() {
184 return _random;
185 }
186 }
187
188 private final static class TLRRef<R extends Random> extends Ref<R> {
189 private final ThreadLocal<R> _random;
190 public TLRRef(final ThreadLocal<R> random) {
191 _random = requireNonNull(random, "Random");
192 }
193 @Override public final R get() {
194 return _random.get();
195 }
196 }
197
198 private static final class Scope<R extends Random> implements Scoped<R> {
199 private final Thread _thread;
200 private final R _random;
201
202 Scope(final Thread thread, final R random) {
203 _thread = requireNonNull(thread);
204 _random = requireNonNull(random);
205 }
206
207 @Override
208 public R get() {
209 return _random;
210 }
211
212 @Override
213 public void close() {
214 if (_thread != Thread.currentThread()) {
215 throw new IllegalStateException(
216 "Try to close scope by a different thread."
217 );
218 }
219 LocalContext.exit();
220 }
221 }
222
223 }
|