Created
August 28, 2015 07:35
-
-
Save NPException/9a2542872fd27609b071 to your computer and use it in GitHub Desktop.
Stateful Random
This file contains 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.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