[英]How do you get to the root cause of a sleep interruption in Java?
我有一些代碼:
public class MyTask implements Runnable {
@Override
public void run() {
// Some code
Thread.sleep();
// Some more code.
}
}
ExecutorService executor = Executors.newCachedThreadPool();
List<MyTask> tasks = getTasks();
for(MyTask t : tasks)
executor.execute(t);
executor.shutdownNow()
if(!executor.awaitTermination(30, TimeUnit.MINUTES)) {
TimeoutException toExc = new TimeoutException("MyAPp hung after the 30 minutes timeout was reached.") // TODO
log.error(toExc)
throw toExc
}
當我從getTasks()
返回多個MyTask
實例運行它時,我變得非常神秘:
[pool-3-thread-3] INFO me.myapp.MyTask - java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
...etc.
這里的問題是沒有根本原因:線程休眠在某些時候只是“中斷”。
所以我問: 什么時候/為什么Thread.sleep()
被中斷了,我該怎么做才能找到異常的根本原因?
執行任務的線程可以通過發出來中斷
future.cancel(true);
對調用executorService.submit(runnable);
函數返回的Future對象executorService.submit(runnable);
如果您遇到許多此類異常,則另一種可能性是整個執行程序服務已關閉
executorService.shutdownNow();
沒有直接的方法可以找出哪個線程實際上打開了interrupted
標志的操作。
作為一個黑客你可以,而不是實現Runnable
擴展Thread
。 然后,您可以在轉發呼叫之前覆蓋interrupt
並獲取堆棧跟蹤。
我不建議將此用於最終代碼,但在追蹤奇怪的中斷時,這可能是唯一的方法。
public class InterruptAwareThread extends Thread {
volatile String interruptedStack = null;
@Override
public void interrupt () {
StringWriter s = new StringWriter();
new Exception().printStackTrace(new PrintWriter(s));
interruptedStack = s.toString();
super.interrupt();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.