簡體   English   中英

你如何找到Java中睡眠中斷的根本原因?

[英]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標志的操作。

引用了Thread.sleep()JavaDoc ,另一個Thread中斷了你的。

拋出:
InterruptedException - 如果有任何線程中斷了當前線程。 拋出此異常時,將清除當前線程的中斷狀態。

用於InterruptedExceptionJavaDoc顯示更多詳細信息:

線程在等待,休眠或以其他方式占用時拋出,並且線程在活動之前或期間被中斷。 有時,方法可能希望測試當前線程是否已被中斷,如果是,則立即拋出此異常。

作為一個黑客你可以,而不是實現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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM