Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap putIfAbsent() is returning null

Tags:

The following program is printing null. I am not able to understand why.

public class ConcurrentHashMapTest {     public static final ConcurrentMap<String, String> map = new ConcurrentHashMap<>(5, 0.9f, 2);      public static void main(String[] args) {         map.putIfAbsent("key 1", "value 1");         map.putIfAbsent("key 2", "value 2");          String value = get("key 3");         System.out.println("value for key 3 --> " + value);     }      private static String get(final String key) {         return map.putIfAbsent(key, "value 3");     } } 

Could someone help me understand the behavior?

like image 424
Niranjan Avatar asked Feb 07 '14 07:02

Niranjan


People also ask

Why does putIfAbsent return null?

The putIfAbsent(Key, value) method of Hashtable class which allows to map a value to a given key if given key is not associated with a value or mapped to null. A null value is returned if such key-value set is already present in the HashMap.

What is putIfAbsent in Java?

The Java HashMap putIfAbsent() method inserts the specified key/value mapping to the hashmap if the specified key is already not present in the hashmap. The syntax of the putIfAbsent() method is: hashmap.putIfAbsent(K key, V value) Here, hashmap is an object of the HashMap class.

What is difference between computeIfAbsent and putIfAbsent?

computeIfAbsent returns "the current (existing or computed) value associated with the specified key, or null if the computed value is null". putIfAbsent returns "the previous value associated with the specified key, or null if there was no mapping for the key".


2 Answers

Problem is that by definition putIfAbsent return old value and not new value (old value for absent is always null). Use computeIfAbsent - this will return new value for you.

private static String get(final String key) {     return map.computeIfAbsent(key, s -> "value 3"); } 
like image 147
Ondřej Stašek Avatar answered Dec 07 '22 12:12

Ondřej Stašek


ConcurrentMap.putIfAbsent returns the previous value associated with the specified key, or null if there was no mapping for the key. You did not have a value associated with "key 3". All correct.

NOTE: Not just for ConcurrentMap, this applies to all implementations of Map.

like image 43
Evgeniy Dorofeev Avatar answered Dec 07 '22 12:12

Evgeniy Dorofeev