ConcurrentHashMap putIfAbsent
时间: 2023-10-17 09:27:12 浏览: 49
ConcurrentHashMap's `putIfAbsent(key, value)` is used to atomically associate the specified key with the given value if it is not already associated with a value in the map. It returns the previous value associated with the key, or `null` if there was no mapping for the key.
Here's an example of how to use `putIfAbsent()`:
```java
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
// putIfAbsent will only add the mapping if there's no existing mapping for the key
Integer previousValue = map.putIfAbsent("key1", 2);
System.out.println(previousValue); // Output: 1
previousValue = map.putIfAbsent("key2", 2);
System.out.println(previousValue); // Output: null
```
In the first `putIfAbsent()` call, since "key1" already has a value of 1 associated with it, the method does not modify the map and returns the previous value (1).
In the second `putIfAbsent()` call, "key2" has no existing mapping, so the method adds a new mapping with the specified value of 2 and returns `null`.
The `putIfAbsent()` operation is atomic, meaning that multiple threads can safely invoke this method concurrently without running into issues like race conditions.