Could a race codition occur when invoking method addId from multiple threads ?
private static Map<String , Long> table;
static {
table = new ConcurrentHashMap<String , Long>();
}
public static void addId(String key, Long value){
if(table.containsKey(key)){
table.remove(key);
}
table.put(key, value);
}
Nothing prevents another thread from putting some value between the
containsKey/removeand theput, so checking if the table already contains a key before putting isn’t really “safe” (or rather, doesn’t really “make sense”).Why don’t you just do
putwill override any previous entry anyway.If you don’t want multiple threads to execute the method concurrently, declare the method as
synchronized.