ConcurrentHashMap 中putIfAbsent 和put的区别

putIfAbsent 源代码

1
2
3
4
5
6
7
8
9
10
11
public V putIfAbsent(K key, V value) {
    Segment<K,V> s;
    if (value == null)
        throw new NullPointerException();
    int hash = hash(key);
    int j = (hash >>> segmentShift) & segmentMask;
    if ((s = (Segment<K,V>)UNSAFE.getObject
         (segments, (j << SSHIFT) + SBASE)) == null)
        s = ensureSegment(j);
    return s.put(key, hash, value, true);
}

put源代码

1
2
3
4
5
6
7
8
9
10
11
public V put(K key, V value) {
      Segment<K,V> s;
      if (value == null)
          throw new NullPointerException();
      int hash = hash(key);
      int j = (hash >>> segmentShift) & segmentMask;
      if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
           (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
          s = ensureSegment(j);
      return s.put(key, hash, value, false);
  }

  前面一段都是一样的,都是先计算hash再同步取值,区别在于 

1
s.put(key, hash, value, true); 和
1
return s.put(key, hash, value, false);<br><br>
1
final V put(K key, int hash, V value, boolean onlyIfAbsent) {

  

1
2
3
4
5
6
7
8
for (HashEntry<K,V> e = first;;) {
                    if (e != null) {
                        K k;
                        if ((k = e.key) == key ||
                            (e.hash == hash && key.equals(k))) {
                            oldValue = e.value;
                            if (!onlyIfAbsent) {
                                e.value = value; //putIfAbsent下不会进入修改e.value, 在key已经存在的情况下++modCount; } break; } e = e.next; }

  

1
onlyIfAbsent 参数,如果key存在的情况下,在putIfAbsent下不会修改,而put下则会修改成新的值<br>测试put
1
2
3
4
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
System.out.println(map.put("1", "1"));
System.out.println(map.put("1", "2"));
System.out.println(map.get("1"));

  结果为:

null
1
2

1
测试putIfAbsent
1
2
3
4
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
System.out.println(map.putIfAbsent("1", "1"));
System.out.println(map.putIfAbsent("1", "2"));
System.out.println(map.get("1"));

 结果为:

null
1
1

 

posted @   谭志宇  阅读(17113)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2009-03-02 用链表写的猴子选大王
2009-03-02 自己写的猴子选大王
点击右上角即可分享
微信分享提示