在我的應用程式中,我生成了一個單執行緒執行器,在執行緒中我正在執行加載 ML 模型/預測的邏輯。如果任何邏輯超過時間限制(4 分鐘),我將關閉執行緒。
但是當應用程式啟動時,當超時發生時,我能夠看到執行緒被關閉的日志。但是程序(預測邏輯)繼續執行。
創建執行緒的代碼片段
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Object> prediction = null;
try {
prediction = service.submit(() -> {
// Execute the requested Document Prediction Engine against the XML Document.
return executeEngine(tenantId, appId, engine, document, predictionParams == null ? new HashMap<>() : new HashMap<>(predictionParams)).get();
});
predictionResult = prediction != null ? (PredictionResult) prediction.get(Long.parseLong(System.getProperty(IDR_INTERNAL_TIMEOUT, "30000")),
TimeUnit.MILLISECONDS) : null;
} catch (TimeoutException e) {
if (prediction != null) {
LOGGER.debug("Task was cancelled with a {} status", (prediction.cancel(true) ? " successful" : " failure"));
}
ExpenseMetrics.internalPredictionTimeout.inc();
String message = "Prediction took more than allowed milliseconds: " Long.parseLong(System.getProperty(IDR_INTERNAL_TIMEOUT, "30000"))
" fileName: " documentFile.getFileName();
if (service != null && !service.isShutdown()) {
service.shutdownNow();
}
service = null;
throw new IDRExmClientException(message, requestId, ErrorCode.INTERNAL_TIMEOUT);
}
if (service != null && !service.isShutdown()) {
service.shutdownNow();
}
service = null;
預測邏輯和超時的代碼片段
List<Callable<Void>> taskList = new ArrayList<Callable<Void>>();
taskList.add(callable1);
taskList.add(callable2);
ExecutorService executor = null;
List<Future<Void>> futures = null;
long s = System.currentTimeMillis();
try {
executor = Executors.newFixedThreadPool(THREAD_POOL);
futures = executor.invokeAll(taskList);
executor.shutdown();
if (!executor.awaitTermination(TOLERANCE_MINUTES, TimeUnit.MINUTES)) {
LOGGER.warn("Document predict thread took more than {} minutes to shutdown", TOLERANCE_MINUTES);
executor.shutdownNow();
}
} catch (InterruptedException iex) {
LOGGER.error("Document predict thread was interrupted", iex);
} finally {
cancelFutures("Predict", futures);
LOGGER.debug("Document predict thread took: {}", (System.currentTimeMillis() - s));
if (executor != null && !executor.isShutdown()) {
executor.shutdownNow();
}
}
executor = null;
uj5u.com熱心網友回復:
來自方法 shutdownNow() 的 Oracle 檔案:
除了盡最大努力停止處理正在執行的任務之外,沒有任何保證。例如,典型的實作將通過 Thread.interrupt 取消,因此任何未能回應中斷的任務可能永遠不會終止。
你可以看到這個答案,它可能對你有幫助: ExecutorService 沒有關閉
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318753.html
上一篇:如何同步慢計算并快取它?
下一篇:與ProcessExplorer的TID對應的System.Threading.Thread的屬性/屬性/欄位是什么?
