Program to use ConcurrentHashMap’s putIfAbsent method



Definition of ConcurrentHashMap’s putIfAbsent method >

public V putIfAbsent(K key, V value)

What do putIfAbsent method do>
If map does not contain specified key, put specified key-value pair in map and return null.
If map already contains specified key, return value corresponding to specified key.


putIfAbsent method is equivalent to writing following code >
synchronized (map){
    if (!map.containsKey(key))
      return map.put(key, value);
     else
      return map.get(key);
   }

Full Program to use putIfAbsent method >
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConcurrentHashMapTest {
   public static void main(String args[]) {
      ConcurrentMap<Integer, String> concurrentHashMap =
                                       new ConcurrentHashMap<Integer, String>();
      concurrentHashMap.put(1, "javaMadeSoEasy");
      System.out.println("concurrentHashMap : "+concurrentHashMap);
     
      System.out.println("\n putIfAbsent method >> "+
                          concurrentHashMap.putIfAbsent(1, "ankit"));
      System.out.println("concurrentHashMap : "+concurrentHashMap);
      System.out.println("\n putIfAbsent method >> "+
                          concurrentHashMap.putIfAbsent(2, "audi"));
      System.out.println("concurrentHashMap : "+concurrentHashMap);
     
   }
}
/*OUTPUT
concurrentHashMap : {1=javaMadeSoEasy}
putIfAbsent method >> javaMadeSoEasy
concurrentHashMap : {1=javaMadeSoEasy}

putIfAbsent method >> null
concurrentHashMap : {2=audi, 1=javaMadeSoEasy}
*/

concurrentHashMap.putIfAbsent(1, "ankit") > returned javaMadeSoEasy because map was already having that key.

concurrentHashMap.putIfAbsent(2, "audi") > putted specified key-value pair in map and  returned null because map wasn’t having that key.



RELATED LINKS>

Program to create method that provides functionality similar to putIfAbsent method of ConcurrentHashMap and to be used with HashMap


Program to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method


eEdit
Must read for you :