我正在尝试用Java实现这个并发策略。我真的不在乎我是在使用streams还是executors,这里最重要的是效率。
我希望在给定的时间期限内并行运行尽可能多的模拟。单个模拟的运行速度比超时快。只要底层线程池中有容量,就应该提交新的模拟。
+----------------+ +--------------+ +------------+
| | param | | Solution | |
| SimCoordinator +-------->+ Simulation +----+----->+ reduce(min)|
| | | | | | |
+-------+--------+ +--------------+ | +------------+
^ |
+--------------------------------------+类看起来像这样:
class SimCoordinator {
double getParam(); //changes every time
double putSolution(Solution s);
}
class Simulation {
Solution run(double param); // takes a while to compute
}协调器向任务提供参数。
然后运行任务并获得解决方案。
必须将解决方案反馈给协调器,这将更改参数的生成方式。
每个解决方案都有一个成本;我希望以最小的成本保存解决方案,并在模拟运行时执行此操作,而不是在截止日期之后。
Simulation.run()是一个很长的操作,因此它应该与其他模拟并发运行。假设我有一个包含N个线程的线程池(或者无论并行流如何工作)。最初,simcoordinator为所有线程提供模拟,当模拟完成时,它会创建新的线程。
解决这类问题的最好方法是什么?
发布于 2019-11-27 22:40:38
所以本质上你所拥有的就是
模拟计时器-根据旧参数及其结果对新参数进行计时计算,即记录最低参数/得分集的计时器计算,即计时器( Consumer<Double, Double>.
所以总而言之,你可以拥有像这样的东西
class SimulationDriver {
private ExecutorService service;
AtomicBoolean finished = new AtomicBoolean();
private ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
private Function<Double, Double> simulation;
private BiFunction<Double, Double, Double> calculateNewParameter;
private Map<Double, Double> results = new ConcurrentHashMap<>();
private SimulationDriver(Function<Double, Double> sim,
BiFunction<Double, Double, Double> newParam) {
simulation = sim;
calculateNewParameter = newParam;
}
public void run(int timeout, Runnable callback, Double... params) {
if (service != null) throw new InvalidStateException("already running");
// initial simulations, one in each thread
service = Executors.newFixedThreadPool(params.length);
for (Double d : params) {
submitForSimulation(d);
}
// after timeout: set finished to prevent new simulations and notify caller
timer.schedule(() -> {
finished.set(true);
service.shutdown();
callback.run(); // tell outside world we're finished
}, timeout, ChronoUnit.SECONDS);
}
void submitForSimulation(Double d) {
if (!finished.get()) { // don't start new simulations after time ran out
CompletableFuture.supplyAsync(() -> simulation.apply(d), service);
result.thenAccept(r -> results.put(d, r)); // store param/result in map
// calculate next parameter and run simulation with that
result.thenAccept(r -> calculateNewParameter.apply(d, r))
.thenAccept(this::submitForSimulation);
}
}
}https://stackoverflow.com/questions/59069046
复制相似问题