ConcurrentHashMap的putIfAbsent


這個方法在key不存在的時候加入一個值,如果key存在就不放入,等價:

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

測試代碼:

public class Test {
    public static void main(String[] args) {
        ConcurrentHashMap<String,String> map=new ConcurrentHashMap<String,String>();
        String temp=map.putIfAbsent("a", "gaoxing");
        System.out.println(map.get("a"));
        temp=map.putIfAbsent("a","nihao");
        System.out.println(map.get("a"));
        temp=map.putIfAbsent("a","gaoxing");
        System.out.println(map.get("a"));
    }
}

結果為

gaoxing
gaoxing
gaoxing

 

ConcurrentHashMap的putIfAbsent用來做緩沖相當不錯,多線程安全的


免責聲明!

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



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