I am trying to understand if below code is thread-safe. I have gone through many many questions in SO but can't seem to find a definite answer.
class Car {
public static Map<String, String> features = new HashMap<>();
static {
features.put("color", "red");
features.put("foo", "bar");
}
public Comparable<?> getValue(String id) {
if(!features.containsKey(id)) {
features.put(id, id);
}
String res = features.get(id);
// some business logic and return stmt.
}
}
We recently encountered unexpected behaviour in our application, wherein, the value returned by getValue("color")
was null. I have been unable to reproduce this issue, but it seems to have happened when two threads were being processed at the same time.
- The
features
map is modified only ingetValue
method if the argument isn't already available in the map. - The issue occurred for an argument which the map is initialised with, in the static block.
- Use case example -
Car c = new Car(); c.getValue("color");
Any help would be much appreciated. Thanks.