Handling InterruptedException in Java

前端 未结 7 708
长发绾君心
长发绾君心 2020-11-22 10:45

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

try{
 //...
} catch(Interrupt         


        
7条回答
  •  名媛妹妹
    2020-11-22 11:45

    I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:

    • Propagating the InterruptException

    • Restore Interrupt state on Thread

    Or additionally:

    • Custom handling of Interrupt

    There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.

    I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/

提交回复
热议问题