考虑以下代码:
public class ExchangeDataSimulatorStartup {
public static ExecutorService executorService = Executors
.newFixedThreadPool(Integer.parseInt(10);
public static void pullData() {
boolean shutdown = false;
while (!shutdown) {
// create a list to hold the Future object associated with Callable
List<Future<String>> futureList = new ArrayList<Future<String>>();
while (stockSymbolsListItr.hasNext()) {
PullStocksData pullStocksData = new PullStocksData(
stockSymbolsListItr.next());
// submit Callable tasks to be executed by thread pool
Future<String> future = executorService.submit(pullStocksData);
// add Future to the list, we can get return value using Future
futureList.add(future);
}
}
}
我需要执行程序服务在应用程序收到关闭信号时关闭。否则执行者应该继续运行。所以我在另一篇文章中看到了以下实现,它说我应该在我的主要功能中添加类似以下代码的内容:
try {
// We will now start our ExchangeDataSimulator
ExchangeDataSimulatorStartup.pullData();
} catch (Exception ex) {
// do some logging
} finally {
executorService.shutdown();
}
我相信上面的代码可以正常工作。它(在 main 方法的 finally block 中关闭执行程序)是正确的方法吗?对此有更好的方法吗?
最佳答案
通常我想给任务一个完成的机会,但时间不会太长。方法见下图:
/**
* Shutdown the given executor service and wait for tasks to finish.
* If tasks do not finish within the given time-out, the executor service is forcibly closed
* (running tasks are interrupted) and tasks that never commenced execution are returned.
* @param es the executor service to shutdown
* @param timeoutSeconds the maximum time in seconds to wait.
* @return null on normal shutdown, else a list of tasks that never commenced execution
*/
public static List<Runnable> shutdown(ExecutorService es, int timeoutSeconds) {
es.shutdown();
if (timeoutSeconds > 0) {
try {
es.awaitTermination(timeoutSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Waiting for executor service tasks completion interrupted.", e);
}
}
return (es.isTerminated() ? null : es.shutdownNow());
}
关于java - 程序结束时关闭java执行器服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23151988/