com.anhth12.lambda.common.random.RandomManager.java Source code

Java tutorial

Introduction

Here is the source code for com.anhth12.lambda.common.random.RandomManager.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhth12.lambda.common.random;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well19937c;

/**
 *
 * @author Tong Hoang Anh
 */
public final class RandomManager {

    private static final long TEST_SEED = 1_234_567_890_123_456_789L;

    private static final Reference<? extends Collection<RandomGenerator>> INSTANCES = new SoftReference<>(
            new ArrayList<RandomGenerator>());
    private static boolean useTestSeed;

    private RandomManager() {
    }

    /**
     * @return a new, seeded {@link RandomGenerator}
     */
    public static RandomGenerator getRandom() {
        if (useTestSeed) {
            // No need to track instances anymore
            return new Well19937c(TEST_SEED);
        }
        RandomGenerator random = new Well19937c();
        Collection<RandomGenerator> instances = INSTANCES.get();
        if (instances != null) {
            synchronized (instances) {
                instances.add(random);
            }
        } // else oh well, only matters in tests
        return random;
    }

    /**
     * <em>Only call in test code.</em> Causes all known instances of {@link RandomGenerator},
     * and future ones, to be started from a fixed seed. This is useful for making
     * tests deterministic.
     */
    public static void useTestSeed() {
        useTestSeed = true;
        Collection<RandomGenerator> instances = INSTANCES.get();
        if (instances != null) {
            synchronized (instances) {
                for (RandomGenerator random : instances) {
                    random.setSeed(TEST_SEED);
                }
                instances.clear();
            }
            INSTANCES.clear();
        }
    }

}