代码改变世界

[hyddd的FindBugs分析记录][M M NP] Synchronize and null check on the same field

2009-02-16 14:39  hyddd  阅读(922)  评论(0编辑  收藏  举报

[M M NP] Synchronize and null check on the same field. [NP_SYNC_AND_NULL_CHECK_FIELD]

Since the field is synchronized on, it seems not likely to be null. If it is null and then synchronized on a NullPointerException will be thrown and the check would be pointless. Better to synchronize on another field.

 

先看一段代码:

public static Timestamp getTableLastUpdateTime(String tableName) {
    Timestamp time 
= null;
    
synchronized (GoodsSysConfig.tableLastUpdateTime) {
       
if (GoodsSysConfig.tableLastUpdateTime != null) {  //这句判断是多余的,可以去掉!
       time 
= GoodsSysConfig.tableLastUpdateTime.get(tableName);
      } 
      
else {
          log.error(
"GoodsSysConfig.tableLastUpdateTime 为空!");
        }
    }
    
return time;
}

这段代码会引发两个BUG警告,一个是:[H C RCN] Nullcheck of value previously dereferenced,另外一个就是这里要介绍的[M M NP] Synchronize and null check on the same field。其实,在[H C RCN] Nullcheck of value previously dereferenced的介绍里面已经提到Synchronize and null check on the same field这个问题了,出现这个BUG的原因是:synchronized (GoodsSysConfig.tableLastUpdateTime) 这里已经对GoodsSysConfig.tableLastUpdateTime这个变量进行了是否为Null的判断,如果为Null,synchronized (...)会抛异常,并且经过synchronized (...)后,GoodsSysConfig.tableLastUpdateTime已经被独占所以 if (GoodsSysConfig.tableLastUpdateTime != null) 这句可以看作是多余的,因为GoodsSysConfig.tableLastUpdateTime不可能为Null。