Skip to content

Instantly share code, notes, and snippets.

@NPException
Created August 28, 2015 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NPException/9a2542872fd27609b071 to your computer and use it in GitHub Desktop.
Save NPException/9a2542872fd27609b071 to your computer and use it in GitHub Desktop.
Stateful Random
import java.lang.reflect.Field;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author NPException
*
* @date 28.08.2015
*
*/
public class StatefulRandom extends Random {
private static final long serialVersionUID = 6409873227820044611L;
private static Field seedField = null;
private transient AtomicLong wrappedSeed;
public StatefulRandom() {
super();
}
public StatefulRandom(final long seed) {
super(seed);
}
private void init() {
try {
seedField = Random.class.getDeclaredField("seed");
seedField.setAccessible(true);
wrappedSeed = (AtomicLong) seedField.get(this);
} catch (final Exception e) {
throw new RuntimeException("oops", e);
}
}
public long extractState() {
if (wrappedSeed == null) {
init();
}
return wrappedSeed.get();
}
public void injectState(final long state) {
if (wrappedSeed == null) {
init();
}
wrappedSeed.set(state);
}
// method to test functionality
public static void main(final String[] args) {
final StatefulRandom random = new StatefulRandom();
random.nextInt();
random.nextInt();
// get seed
final long currentState = random.extractState();
System.out.println(random.nextInt());
random.injectState(currentState);
System.out.println(random.nextInt());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment