i am not understanding how below code snippet can be made thread safe.
class MapUser {
Map<String,Integer> map = new ConcurrentHashMap<String,Integer>
public void addToMap(String str, Integer val){
if(checkMagicString(str)){
map.put(str,val);
}
}
private boolean checkMagicString(String str){
//some logic to check Magic
//this logic involved operation on the String parameter str i.e. subString,toCharArray etc
}
}
Note the method addToMap is called by multiple threads concurrently. I want to make sure that thread safety is maintained. By using ConcurrentHashMap I can ensure that threads will add the values to it safely.
However I am not understanding how method checkMagicString(String str) can remain thread safe? Is the only way to do it to make it synchronized? Or should the caller method addToMap be made synchronized?
Please note that I am not accessing the map inside checkMagicString method.
Even if you do make
checkMagicStringatomic, it will not make the sequenceatomic, since a thread can be interrupted between the
ifcheck and themap.putcall and thus you might end up with two threads inserting the same string. You need to lock the entire sequence to be safe.Edit: If the above is acceptable behavior (i.e. two threads inserting the same key and overwriting the value) and
checkMagicStringdoes not operate on shared state then your code is fine as it is.