public final class RandomRegistry extends StaticObject
Random
engine used for the GA. The
RandomRegistry
is thread safe. The registry is initialized with the
ThreadLocalRandom
PRNG, which has a much better performance behavior
than an instance of the Random
class. Alternatively, you can
initialize the registry with one of the PRNG, which are being part of the
library.
Setup of a global PRNG
public class GA {
public static void main(final String[] args) {
// Initialize the registry with a ThreadLocal instance of the PRGN.
// This is the preferred way setting a new PRGN.
RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal());
// Using a thread safe variant of the PRGN. Leads to slower PRN
// generation, but gives you the possibility to set a PRNG seed.
RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadSafe(1234));
...
final GeneticAlgorithm<DoubleGene, Double> ga = ...
ga.evolve(100);
}
}
public class GA {
public static void main(final String[] args) {
...
final GeneticAlgorithm<DoubleGene, Double> ga = ...
final LCG64ShiftRandom random = new LCG64ShiftRandom(1234);
try (Scoped<Random> scope = RandomRegistry.scope(random)) {
// Easy access the random engine of the opened scope.
assert(scope.get() == random);
// Only the 'setup' step uses the new PRGN.
ga.setup();
}
ga.evolve(100);
}
}
Random
,
ThreadLocalRandom
,
LCG64ShiftRandom
Modifier and Type | Method and Description |
---|---|
static Random |
getRandom()
Return the global
Random object. |
static void |
reset()
Set the random object to it's default value.
|
static <R extends Random> |
scope(R random)
Opens a new
Scope with the given random engine. |
static void |
setRandom(Random random)
Set the new global
Random object for the GA. |
static void |
setRandom(ThreadLocal<? extends Random> random)
Set the new global
Random object for the GA. |
public static Random getRandom()
Random
object.Random
object.public static void setRandom(Random random)
Random
object for the GA. The given
Random
must be thread safe, which is the case for the
default Java Random
implementation.
Setting a thread-local random object leads, in general, to a faster
PRN generation, because the given Random
engine don't have to be
thread-safe.random
- the new global Random
object for the GA.NullPointerException
- if the random
object is null
.setRandom(ThreadLocal)
public static void setRandom(ThreadLocal<? extends Random> random)
Random
object for the GA. The given
Random
don't have be thread safe, because the given
ThreadLocal
wrapper guarantees thread safety. Setting a
thread-local random object leads, in general, to a faster
PRN generation, when using a non-blocking PRNG. This is the preferred
way for changing the PRNG.random
- the thread-local random engine to use.NullPointerException
- if the random
object is null
.public static void reset()
ThreadLocalRandom
PRNG.© 2007-2014 Franz Wilhelmstötter (2014-03-07 19:35)