[英]ExecutorService that rethrows exceptions
我需要使用任何Executor
或ExecutorService
執行任務。 該任務( Callable
或Runnable
)應該無限運行,但是在發生任何異常的情況下,應將其重新拋出給提交任務的線程。
我知道future.get()
會為我拋出ExecutionException
:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(new Task());
future.get();
但是,在晴天的情況下,我會無限期地阻止future.get()
,因此無法使用它。
有可能有任何Executor
程序在基礎任務失敗時簡單地引發異常嗎?
我認為僅使用執行程序是不可能做到這一點的。
您可以考慮在Task中使用try-catch塊,並將異常添加到catch塊中的隊列中。
try{
//perform task
}catch(Exception e){
queue.offer(e)
}
創建一個從隊列讀取異常的線程。
public void run() {
Exception e;
try {
e = q.take();
e.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.