Handling InterruptedException in Java

前端 未结 7 947
长发绾君心
长发绾君心 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:27

    I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

    One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

    EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

提交回复
热议问题