如果我有下面的代碼,它工作正常:Java ExecutorService - 如果awaitTermination()失敗會怎麼樣?
ExecutorService service = Executors.newFixedThreadPool(100);
[....]
List<Future<SomeObject>> futures = service.invokeAll(callables);
for (Future f : futures) {
f.get();
}
// shutdown the service after all Callables are finished.
service.shutdown();
boolean serviceIsShutDown = service.awaitTermination(5, TimeUnit.SECONDS);
if (serviceIsShutDown) {
System.out.println("Service terminated normally. All ok.");
} else {
// What if it's not shutDown?
[...]
// this?
//service = null;
}
問題:如果呼叫
boolean serviceIsShutDown = service.awaitTermination(5, TimeUnit.SECONDS);
返回false,因爲超時命中?
我猜ExecutorService中的線程將保持WAIT狀態。什麼是最好的解決方案? 將服務設置爲null並讓GarbageCollector刪除它?但是相關的線程會發生什麼?由於還有參考資料,它會不會被垃圾收集?
該代碼通常有效,但只是好奇。如果返回false,該怎麼辦?
取決於你想要做什麼。你可以試着用.shutdown()強制關機,或者用shutdownNow()關機。 – jordaniac89
您好Joschi,您已經按照這篇文章改變了關機邏輯:http://stackoverflow.com/questions/4958330/java- executorservice-awaittermination-of-all-recursively-created-tasks/39295555#39295555 –
嗨,謝謝大家的回答! – Joschi