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

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

代码首先是这样的  

 public static List getKeyInvoiceOpeningResList(
            String key) {
        List  list = invoiceOpeningListMap.get(key);
        if (list == null) {
            list = new ArrayList();
            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 getKeyInvoiceOpeningResList(
            String key) {
        List  list = invoiceOpeningListMap.get(key);
        if (list == null) {
            list = new ArrayList();
            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://stackoverflow.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_第1张图片

要使用返回值

修改如下 findbugs不在报错

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

参考 :

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

你可能感兴趣的:(多线程,工具使用)