美文网首页
修Sonar学Java(1)— — 你真的了解Interrupt

修Sonar学Java(1)— — 你真的了解Interrupt

作者: 华安火车迷 | 来源:发表于2018-02-11 11:16 被阅读0次

    大家知道改这个SONAR 背后的隐患点吗?

    InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the fact that the thread was interrupted will be lost. Instead, InterruptedExceptions should either be rethrown - immediately or after cleaning up the method's state - or the thread should be re-interrupted by calling Thread.interrupt() even if this is supposed to be a single-threaded application. Any other course of action risks delaying thread shutdown and loses the information that the thread was interrupted - probably without finishing its task.

    Similarly, the ThreadDeath exception should also be propagated. According to its JavaDoc:

    If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

    Noncompliant Code Example

    public void run () {
      try {
        while (true) {
          // do stuff
        }
      }catch (InterruptedException e) { // Noncompliant; logging is not enough
        LOGGER.log(Level.WARN, "Interrupted!", e);
      }
    }
    

    推荐一篇文章

    Java 理论与实践
    处理 InterruptedException 捕捉到它,然后怎么处理它?

    相关文章

      网友评论

          本文标题:修Sonar学Java(1)— — 你真的了解Interrupt

          本文链接:https://www.haomeiwen.com/subject/kxyktftx.html