Last active
February 6, 2017 13:37
-
-
Save dhadka/f5a3adc36894cc6aebcaf3dc1bbcef9f to your computer and use it in GitHub Desktop.
Creates a synchronized (thread-safe) version of the Mersenne Twister random number generator. Each thread is assigned a different instance of the MersenneTwister.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.SecureRandom; | |
import java.util.Random; | |
import org.apache.commons.math3.random.MersenneTwister; | |
public class SynchronizedMersenneTwister extends Random { | |
private static final long serialVersionUID = -4586969514356530381L; | |
private static Random SEEDER; | |
private static SynchronizedMersenneTwister INSTANCE; | |
private static ThreadLocal<MersenneTwister> LOCAL_RANDOM; | |
static { | |
SEEDER = new SecureRandom(); | |
LOCAL_RANDOM = new ThreadLocal<MersenneTwister>() { | |
@Override | |
protected MersenneTwister initialValue() { | |
synchronized (SEEDER) { | |
return new MersenneTwister(SEEDER.nextLong()); | |
} | |
} | |
}; | |
INSTANCE = new SynchronizedMersenneTwister(); | |
} | |
private SynchronizedMersenneTwister() { | |
super(); | |
} | |
public static SynchronizedMersenneTwister getInstance() { | |
return INSTANCE; | |
} | |
private MersenneTwister current() { | |
return LOCAL_RANDOM.get(); | |
} | |
public synchronized void setSeed(long seed) { | |
current().setSeed(seed); | |
} | |
public void nextBytes(byte[] bytes) { | |
current().nextBytes(bytes); | |
} | |
public int nextInt() { | |
return current().nextInt(); | |
} | |
public int nextInt(int n) { | |
return current().nextInt(n); | |
} | |
public long nextLong() { | |
return current().nextLong(); | |
} | |
public boolean nextBoolean() { | |
return current().nextBoolean(); | |
} | |
public float nextFloat() { | |
return current().nextFloat(); | |
} | |
public double nextDouble() { | |
return current().nextDouble(); | |
} | |
public synchronized double nextGaussian() { | |
return current().nextGaussian(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment