Is the following code thread safe? The class SlidingTimeWindowCountGauge is already thread safe. The question is around the double check locking code + the regular non-concurrent hashmap.
I would like to lazily create entries in the hashmap. Entries should only be created once and reused thereafter. I would like to avoid locking if possible.
public class InstrumentedCaller {
private final Map<String, SlidingTimeWindowCountGauge> nameToCountGauge = new HashMap<>();
private SlidingTimeWindowCountGauge getGaugeLazy(final String name) {
SlidingTimeWindowCountGauge gauge = nameToCountGauge.get(name);
if (gauge != null) {
return gauge;
}
synchronized (this) {
if (nameToCountGauge.containsKey(name)) {
return nameToCountGauge.get(name);
}
final SlidingTimeWindowCountGauge newGauge = new SlidingTimeWindowCountGauge(1, TimeUnit.MINUTES);
this.nameToCountGauge.put(name, newGauge);
return newGauge;
}
}
private void markCall(final String callName) {
SlidingTimeWindowCountGauge gauge = getGaugeLazy(callName);
gauge.mark();
}
public void doCall1() {
markCall("call1");
}
public void doCall2() {
markCall("call2");
}
}