代码之家  ›  专栏  ›  技术社区  ›  John

在并行执行模拟时找到正确的随机种子数

  •  3
  • John  · 技术社区  · 8 年前

    我有这样一门课:

    public class Class implements Runnable {
        ...
        public void run() {
    
            ArrayList<Integer> simulations = new ArrayList<>();
            ArrayList<Random> randomSeedsList = new ArrayList<>();
    
            for (int run = 0; run < getNumberOfSimulations(); run++) {
                simulations.add(run);
                Random random = new Random(run);
                randomSeedsList.add(run, random);
            }
            ...
            simulations.parallelStream().forEach(run -> runSimulation(run,...))
        }
    }
    

    现在 runSimulation 执行许多操作、调用/创建其他类等。在许多执行点(甚至在这些其他类的内部),调用此函数可根据您所处的特定运行/模拟获取下一个随机数:

    rantInt(arg1,arg2,run) 
    

    rantInt在以下类别中定义:

    public class Util {
        // get random integer between min and max (inclusive)
        public static int randInt(int min, int max, int run) {
            return Class.randomSeedsList.get(run).nextInt((max - min) + 1) + min;
        }
    }
    

    问题是,我希望每次运行N个并行模拟时,每个模拟的结果都是完全相同的,通过这个实现,我得到了相同的结果-但这很难看,因为我必须通过 run 通过大量函数调用和类构造函数实现变量,这样我就可以在执行这些模拟代码中的某些函数时知道它的值 rantInt .

    我的问题是:有没有更优雅的方法?我在这个实现中遗漏的任何其他设计原则都可以获得相同的结果,而无需携带 跑 到处都是变量?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Holger    8 年前

    您可以将 Random 当前线程执行模拟的实例。由于模拟和线程之间没有1:1的关系,因此应将此关联封装在专用的管理器类中,该类强制初始化和清理线程局部变量,并拒绝无效使用:

    public class RandomManager {
        private static ThreadLocal<Random> RANDOMS = new ThreadLocal<>();
        public static void withRandom(Random rnd, Runnable run) {
            Objects.requireNonNull(rnd);
            Objects.requireNonNull(run);
            if(RANDOMS.get() != null) throw new IllegalStateException("nested invocation");
            RANDOMS.set(rnd);
            try {
                run.run();
            }
            finally {
                RANDOMS.remove();
            }
        }
        // get random integer between min and max (inclusive)
        public static int randInt(int min, int max) {
            Random r = RANDOMS.get();
            if(r == null) throw new IllegalStateException("not within withRandom(...)");
            return r.nextInt((max - min) + 1) + min;
        }
    }
    

    这样,当前执行模拟的每个线程都可以与 随机的 实例,而尝试访问 随机的 不执行模拟的线程被拒绝,并且一个线程可以一个接一个地执行多个模拟,每个模拟都与不同的 随机的 实例,但不能嵌套模拟。检测到并拒绝嵌套执行的尝试。另一个重要属性是,线程本地值在之后被删除,因此如果线程被重用用于其他目的,则不会留下任何垃圾,这适用于并行流使用的工作线程。

    管理 随机的 通过简单地使用任意 Runnable s来描述可能要求局部随机值的操作。

    然后,使用的代码可以是

    class YourClass implements Runnable {
        public void run() {
            ArrayList<Random> randomSeedsList = new ArrayList<>();
            int total = getNumberOfSimulations();
            for (int run = 0; run < total; run++) {
                randomSeedsList.add(new Random(run));
            }
            assert randomSeedsList.size() == total;
            IntStream.range(0, total).parallel()
                     .forEach(run -> RandomManager.withRandom(randomSeedsList.get(run),
                                                              ()->runSimulation(run, …)));
        }
    }
    

    或者,如果整数索引仅用于维护与 随机的 实例,您可以进一步简化:

    class YourClass implements Runnable {
        public void run() {
            List<Random> randomSeedsList
                = IntStream.range(0, getNumberOfSimulations())
                           .mapToObj(Random::new)
                           .collect(Collectors.toList());
    
            randomSeedsList.parallelStream()
                           .forEach(random -> RandomManager.withRandom(random,
                                                                       ()->runSimulation(…)));
        }
    }