[問題解決]Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.


背景以及問題

記處理一次sonarqube掃出來的代碼問題。

代碼

public void main() {
    try {
        Thread.sleep(100L);
    } catch (Exception e) {
        log.error("err. "e);
    }
} 

sonar提示問題

Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.為何是問題? 

這里希望

  1.  Thread.currentThread().interrupt(); 重新標記一下線程中斷狀態
  2.  或者 再次throw InterruptedException

所以 對應1的正確寫法 

public void main() {
    try {
        Thread.sleep(100L);
    } catch (InterruptedException e) {
        log.error("err", e);
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        log.error("err. ",e);
    }
}

原因

java interrup()函數會中斷線程(本質更新線程為中斷狀態)。若sleep()函數檢測到線程中斷(interrupt()函數觸發) 會拋 InterruptedException, 被catch住后線程中斷狀態更新為未中斷(參考:https://www.codenong.com/cs106837995/)。

sonar檢測到該問題會提示此種潛在邏輯,防止忽略該潛在風險而導致代碼bug。

所以,正確處理方式需要手動再次觸發一下Thread.currentThread().interrupt();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM