Bug: Return value of putIfAbsent is ignored, but list is reused

时间:2021-07-10 18:46:56

这个错误是findbugs插件找出来的问题.

代码首先是这样的  

 public static List<InvoiceDTO> getKeyInvoiceOpeningResList(
            String key) {
        List<InvoiceDTO>  list = invoiceOpeningListMap.get(key);
        if (list == null) {
            list = new ArrayList<InvoiceDTO>();
            invoiceOpeningListMap.put(key, list);
        }
        return list;
    }

提示Bug: Sequence of calls to java.util.concurrent.ConcurrentHashMap may not be atomic in com..XXX类

参考了网上的信息  修改为

 public static List<InvoiceDTO> getKeyInvoiceOpeningResList(
            String key) {
        List<InvoiceDTO>  list = invoiceOpeningListMap.get(key);
        if (list == null) {
            list = new ArrayList<InvoiceDTO>();
            invoiceOpeningListMap.putIfAbsent(key, list);
        }
        return list;
    }
    

putIfAbsent这个方法在key不存在的时候加入一个值,如果key存在就不放入,等价:

   if (!map.containsKey(key)) 
      return map.put(key, value);
  else
       return map.get(key);

解决了多线程同时做这个操作的并发问题

但是改好后依然提示

Bug: Return value of putIfAbsent is ignored, but list is reused in com.XXX类


继续找到https://*.com/questions/21251134/how-to-resolve-the-findbug-sequence-of-calls-to-java-util-concurrent-concurrenth

得到答案:

Bug: Return value of putIfAbsent is ignored, but list is reused

要使用返回值

修改如下 findbugs不在报错

 public static List<InvoiceDTO> getKeyInvoiceOpeningResList(
            String key) {
        List<InvoiceDTO>  list = invoiceOpeningListMap.get(key);
        if (list == null) {
            list = new ArrayList<InvoiceDTO>();
            list = invoiceOpeningListMap.putIfAbsent(key, list);
        }
        return list;
    }

参考 :

https://www.cnblogs.com/gaoxing/p/4271749.html