2017-01-19 54 views
0

我是新來的Java併發編程,並嘗試異步啓動一些Callables。但是,代碼似乎擋住了我PROGRAMM流,其中Callables被賦予的ExecutorService es.invokeAll(tasks)併發執行Java 8

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年1月19日16:06:06474 INFO [主要] de.cgh.screwminer.service.measurement.MeasurementService (MeasurementService.java:127) - Submmitting任務

2017-01 -19 16:06:08,477錯誤[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年1月19日16:06:08482 INFO [主] de.cgh.screwminer.service.measurement.MeasurementService (MeasurementService.java:132) - 提交任務

回答

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 

所以是invokeAll任務完成。

你可以做的只是在類中執行Executor,並在forEach()中提交每個任務,這將執行相同的操作。然後你會得到一份你應該檢查錯誤的期貨清單。

你可以做這樣的事情:

getSensors().forEach(s -> { 
    CompletableFuture<Void> cf = (s -> writerService.openWriteConnection(s)).exceptionally(ex -> errorhandling) 
    exec.submit(cf) 
}); 

CompletableFuture是Java8功能,並允許您控制錯誤很好,你不必問期貨,如果他們成功完成(這往往會導致非意外記錄錯誤)