package devmanuals.com; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import java.util.Set; class CMPutIfAbsent1 implements Runnable { String name; ConcurrentMap cm; public CMPutIfAbsent1(ConcurrentMap cm, String name) { this.name = name; this.cm = cm; } public void run() { try { cm.put(1, "A"); cm.put(2, "B"); cm.put(3, "C"); cm.put(4, "D"); cm.put(5, "E"); System.out.println(name + " maps the element : " + cm); System.out.println(name + " represents the set of keys: " + cm.keySet()); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } class CMPutIfAbsent2 implements Runnable { String name; ConcurrentMap cm; public CMPutIfAbsent2(ConcurrentMap cm, String name) { this.name = name; this.cm = cm; } public void run() { try { boolean j = cm.remove(3, "C"); System.out.println(name + " removes the element : " + j); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } class CMPutIfAbsent3 implements Runnable { String name; ConcurrentMap cm; public CMPutIfAbsent3(ConcurrentMap cm, String name) { this.name = name; this.cm = cm; } public void run() { try { Set s = cm.keySet(); System.out .println(name + " represents " + "the set of keys : " + s); // here the implementation of this method // will return the previous value associated with key '4' String st = cm.putIfAbsent(4, "D"); System.out.println(name+" returns the previous value : " + st); // here the implementation of this method // will return the 'null' value associated with key '4' st = cm.putIfAbsent(3, "C"); System.out.println(name+" returns : " + st); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } public class CMPutIfAbsent { public static void main(String[] args) { ConcurrentMap cm = new ConcurrentHashMap(); Runnable a = new CMPutIfAbsent1(cm, "A"); Runnable b = new CMPutIfAbsent2(cm, "B"); Runnable c = new CMPutIfAbsent3(cm, "C"); new Thread(a).start(); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(b).start(); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(c).start(); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } }