请考虑以下代码:
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);
}
}
}
每当应用程序收到关闭信号时,我都需要执行器服务才能关闭。否则执行者应继续运行。所以我在另一篇帖子中看到了以下实现,其中说我应该在我的main函数中添加类似下面的代码:
try {
// We will now start our ExchangeDataSimulator
ExchangeDataSimulatorStartup.pullData();
} catch (Exception ex) {
// do some logging
} finally {
executorService.shutdown();
}
我相信上面的代码会正常工作。它是(在主方法的finally块中关闭执行程序)正确的方法吗?有没有更好的方法呢?
答案 0 :(得分:1)
按照OP中的说明进行操作将使所有任务等待停止。但是,如果您使用executorService.shutdownNow()
答案 1 :(得分:1)
通常我想让任务有机会完成,但不会太久。请参阅下面显示的方法:
/**
* 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());
}
答案 2 :(得分:1)
您可以添加代码以关闭ExecutorService作为在应用程序关闭时自然运行的shutdownhook。
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
//shutdown executor service here
}
});
使用这段代码,它将在结束应用程序时关闭。
注意:只有在正常关闭应用程序时才会调用此方法。如果它被调试器终止或被进程终止,则不会执行上述操作。我实际上不确定它是否在应用程序崩溃时被执行但我只是假设它没有。