ConcurrentHashMap中的putIfAbsent方法的使用以及返回值的含义

public V putIfAbsent(@NotNull K key, 
@NotNull V value)

putIfAbsent方法主要是在向ConcurrentHashMap中添加键—值对的时候,它会先判断该键值对是否已经存在。

如果不存在(新的entry),那么会向map中添加该键值对,并返回null。 
如果已经存在,那么不会覆盖已有的值,直接返回已经存在的值。 
相当于:

 V v = map.get(key);
 if (v == null)
     v = map.put(key, value);
 return v;

返回值: 
(1)如果是新的记录,那么会向map中添加该键值对,并返回null。 
(2)如果已经存在,那么不会覆盖已有的值,直接返回已经存在的值。

测试代码:

package com.tao.client;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by michael on 17-7-13.
 */
public class Test {

    public static void main(String[] args) {

        //测试一下currentHashMap.putIfAbsent()

        Map<Long, String> clientMap = new ConcurrentHashMap<>();

        System.out.println("首先打印空的clientMap");
        System.out.println("clientMap: " + clientMap);
        System.out.println();

        //在空的clientMap中添加一个新的记录
        System.out.println("在空的clientMap中添加一个新的记录");
        System.out.println("添加之前的clientMap: " + clientMap);
        long netId = 1234567L;
        String str1 = "michael";
        String result = clientMap.putIfAbsent(netId, str1);
        System.out.println("添加之后的clientMap: " + clientMap);
        System.out.println("查看返回值result: " + result);
        System.out.println();

        //重复添加
        System.out.println("重复添加上一次的记录");
        System.out.println("添加之前的clientMap: " + clientMap);
        String result2 = clientMap.putIfAbsent(netId, str1);
        System.out.println("添加之后的clientMap: " + clientMap);
        System.out.println("查看返回值result: " + result2);
        System.out.println();

    }
}

输出结果: 
控制台输出结果

原文地址:https://www.cnblogs.com/exmyth/p/9078898.html