java - 可调用对象的执行顺序不一致
问题描述
我有这段代码,我在其中执行一组可调用对象,我需要一组来完成它的所有工作,然后再触发下一组。这段代码似乎工作正常,但有时下一组会在时间之前开始运行。这里有什么问题?
private void executeSubGraph(QuestExecutionContext ctx, Set<Activity> subGraph, int progressAfterRan) {
ExecutorService pool = Executors.newFixedThreadPool(16);
subGraph.forEach(a -> {
ActivityRunner<? extends Activity> runner = activityRunnerFactory.getRunner(ctx, a);
if (runner != null) {
Callable<List<PortValuePart>> runnerCallable = () -> {
try {
LOG.info("Running {} in {}", a, a.getClass() );
List<PortValuePart> result = runner.call();
LOG.info("Result of {} in {} is {}", a, a.getClass(), result);
if (result != null) {
result.forEach(r -> resultProcessor.processResult(new PortValuePartEnvelope(r)));
}
return result;
} catch (Exception e) {
LOG.warn("Exception for {} in {}", a, runner.getClass(), e);
resultProcessor.processResult(Progress.failed(ctx.getId(), e));
throw new RuntimeException(e);
}
};
Future<List<PortValuePart>> p = pool.submit(runnerCallable);
} else {
LOG.warn("No runner found for activity {}", a);
resultProcessor.processResult(Progress.failed(ctx.getId(), new RuntimeException("No runner found for activity " + a)));
throw new RuntimeException("No runner found for activity " + a);
}
});
pool.shutdown();
try {
pool.awaitTermination(WAIT_TIME_MILLIS, TimeUnit.MILLISECONDS);
resultProcessor.processResult(Progress.running(ctx.getId(), progressAfterRan));
} catch (InterruptedException e) {
throw new PlatformException("Execution interrupted.");
}
}
解决方案
请注意,ExecutorService.awaitTermination
如果超时不会抛出异常;它只是返回false
。如果您想确保下一个调用不会与这些调用同时运行,您可能应该使用返回值,并且如果花费的时间太长,可能会抛出异常(并终止任务)。
推荐阅读
- r - R:合并数据,同时保留重复数据集的值
- java - 如何在 Netbeans 中以 Executable(.exe) 导出我的 Java 项目?
- asp.net-core - 从 ASP.NET Core 中间件管道写入控制台
- django - 为在 Windows Server 2016 IIS 上运行的 Django 项目运行“git pull”
- vue.js - 从 vue build 更改资产的根目录
- excel - 进行更改的返回用户
- javascript - 架构的 Node.js 问题。用户 ID 验证错误
- windows - 如何让 Jena Fuseki 在 cygwin bash shell 中运行?
- ruby-on-rails - 如何禁用 webpacker 加载器?
- javascript - 有没有办法在功能组件中将数据传递给 props.children