我不熟悉使用java并发编程并尝试异步启动某些Callables
。但代码似乎阻止了我的程序流,其中Callables
被赋予执行者服务es.invokeAll(tasks)
:
public void checkSensorConnections(boolean fireEvent) {
List<Callable<Void>> tasks = new ArrayList<>();
getSensors().forEach(sensor -> {
tasks.add(writerService.openWriteConnection(sensor));
tasks.add(readerService.openReadConnection(sensor));
});
try {
LOG.info("Submmitting tasks");
ExecutorService es = Executors.newWorkStealingPool();
es.invokeAll(tasks);
LOG.info("Tasks submitted");
} catch (InterruptedException e) {
LOG.error("could not open sensor-connections", e);
error(MeasurmentScrewMinerError.OPEN_CONNECTION_ERROR);
}
}
我有一些控制程序流程的日志语句。正如您所看到的那样,执行会一直等到两个任务执行完毕。
2017-01-19 16:06:06,474 INFO [main] de.cgh.screwminer.service.measurement.MeasurementService (MeasurementService.java:127) - 提交任务
2017-01-19 16:06:08,477 ERROR [pool-2-thread-2] de.cgh.screwminer.service.measurement.SensorReadService (SensorReadService.java:68) - 传感器Drehmoment读连接可以 不能打开java.net.SocketTimeoutException:接收超时...
2017-01-19 16:06:08,477 错误[pool-2-thread-4] de.cgh.screwminer.service.measurement.SensorReadService (SensorReadService.java:68) - 传感器Kraft读连接不能 打开java.net.SocketTimeoutException:接收超时...
2017-01-19 16:06:08,482 INFO [main] de.cgh.screwminer.service.measurement.MeasurementService (MeasurementService.java:132) - 提交的任务
答案 0 :(得分:0)
来自invokeAll的Javadoc:
Returns:
a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed
所以是的,调用所有任务都已完成。
你可以做的只是在课堂上执行Executor并在forEach()中提交每个任务,这样做也是如此。然后,您将获得一份应该检查错误的期货清单。
你可以这样做:getSensors().forEach(s -> {
CompletableFuture<Void> cf = (s -> writerService.openWriteConnection(s)).exceptionally(ex -> errorhandling)
exec.submit(cf)
});
CompletableFuture是一个Java8功能,可让您很好地控制错误,因为您不必询问期货是否成功完成(这通常会导致意外的未记录错误)