Instead of using synchronization, I used AtomicReference as a substitute:
private AtomicReference<HashMap<String,String>> a = new AtomicReference<HashMap<String,String>>();
public String initPool(HashMap<String,String> latest){
HashMap<String, String> old = a.get();
if(old!=null){
Set<String> key = a.get().keySet();
for(String val: key){
if(!latest.containsKey(val)){
a.get().put(val,latest.get(val));
return returnObj(val);
}else{
return returnObj(val);
}
}
}else{
a.compareAndSet(old, latest);
return null;
}
return null;
}
public String returnObj(String key){
HashMap<String,String> upd = a.get();
return upd.get(key);
}
The sample data to be added into the collection are:
"a","a"
"b","b"
"c","c"
"a","a"
I intend to simulate this under a condition whereby multiple users will call the function above and supply the
sample data as mentioned above. How can I achieve this? Your help is kindly appreciated.
Thank You.