Open
Description
// 线程 A
map.putIfAbsent(key, value);
// 线程 B
map.putIfAbsent(key, anotherValue);
eg:
public static void main(String[] args) {
Map<String, Integer> map = new ConcurrentHashMap<>();
// 初始时 map 为空
// 计算键 "key1" 对应的值,如果不存在则根据计算逻辑生成值
Integer value1 = map.putIfAbsent("key1", 1);
System.out.println("map = " + map); // 输出: map = {key1=1}
System.out.println("value1 = " + value1); // 输出: value1 = 1
// 再次计算键 "key1" 对应的值,由于键已存在,直接返回已有的值
Integer value2 = map.putIfAbsent("key1", 2);
System.out.println("map = " + map); // 输出: map = {key1=1}
System.out.println("value2 = " + value2); // 输出: value2 = 1
}
以上操作也并不会实现预期的 (key, anotherValue)。
Metadata
Metadata
Assignees
Labels
No labels