What kind of behaviour causes an interrupted exception?

后端 未结 7 730
说谎
说谎 2020-12-24 13:15

I\'m relatively new to Threading in Java and I\'ve noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.

What kind of behaviour causes th

相关标签:
7条回答
  • 2020-12-24 13:36

    Some advices from Java Concurrency in Practice:

    • Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
    • Restore the interruption status so that code higher up on the call stack can deal with it.
    • Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
    0 讨论(0)
  • 2020-12-24 13:38

    It happens when something calls interrupt() on the thread. This article by Brian Goetz explains the interruption mechanism and how you should handle InterruptedExceptions:

    "The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."

    "If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."

    0 讨论(0)
  • 2020-12-24 13:38

    As others have said, it is caused by some other thread calling interrupt() on the Thread object that is sleeping.

    What this means in plain english, is that some other thread has decided to cancel the sleeping thread. The try/catch block is there so you can gracefully handle the cancellation of the thread, and safely clean up any resources, or shut down whatever operation it was doing correctly.

    If you don't actually need to do any of that, then yes, you still need an empty catch block. But that's Java for you...​​​​​​​​​​​​​​​​​​​​

    0 讨论(0)
  • 2020-12-24 13:39

    Well if some other Thread calls thread.interupt(), while the thread is sleeping, you'll get the Exception. And yes, you can probably just put try..catch arround the sleep() and ignore it ;)

    0 讨论(0)
  • 2020-12-24 13:40

    From the javadocs:

    Class InterruptedException

    Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

    Hope that answers your question.

    0 讨论(0)
  • 2020-12-24 13:48

    The primary case is when someone calls Thread.interrupt() on your thread.

    It may be safer to throw a RuntimeException if it happens when you're really not expecting it, but for very simple cases you can probably ignore it.

    0 讨论(0)
提交回复
热议问题