package devmanuals.com; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import java.util.Set; class CMReplace1 implements Runnable { ConcurrentMap cmp; String name; public CMReplace1(String name, ConcurrentMap cmp) { this.cmp = cmp; this.name = name; } public void run() { System.out.println(name + " maps the element "); cmp.put(1, "A"); cmp.put(3, "C"); cmp.put(4, "D"); System.out.println(cmp); System.out.println("Size of Map = " + cmp.size()); Set s = cmp.keySet(); System.out.println("Key set of map = " + s); // here implementation of this method will show the previously // associated value with specified key. String s2 = cmp.replace(2, "E"); System.out.println("Previously associated value of '2' was : " + "'" + s2 + "'"); try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } } } class CMReplace2 implements Runnable { String name; ConcurrentMap cmp; public CMReplace2(String name, ConcurrentMap cmp) { this.cmp = cmp; this.name = name; } public void run() { try { // here implementation of method will return the previously // associated value. cmp.put(2,"E"); String s = cmp.replace(2, "D"); System.out.println("Previously associated value of '2' was : " + "'" + s + "'"); // here implementation of method will return null it shows //there is no mapping exist into the map. String s1 = cmp.replace(2, "B"); System.out.println("Previously associated value of '2' was : " + "'" + s1 + "'"); Thread.sleep(1500); System.out.println("Set of key = " + cmp.keySet()); System.out.println("Size of Map = " + cmp.size()); } catch (InterruptedException e) { e.printStackTrace(); } } } public class CMReplace { public static void main(String args[]) { ConcurrentMap cmp = new ConcurrentHashMap(); Runnable a = new CMReplace1("A", cmp); new Thread(a).start(); try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } Runnable b = new CMReplace2("B", cmp); new Thread(b).start(); } }