I need to review this code:
import java.util.HashMap;
import java.util.Map;
// REVIEW
public abstract class Digest {
private Map<String, byte[]> cache = new HashMap<>();
public byte[] digest(String input) {
byte[] result = cache.get(input);
if (result == null) {
synchronized (cache) {
result = cache.get(input);
if (result == null) {
result = doDigest(input);
cache.put(input, result);
}
}
}
return result;
}
protected abstract byte[] doDigest(String input);
}
Should I mark
cache
as volatile ?
I have doubts because we usecashe.get
in method body instead of directcashe
Would it make sense to replace the map with
ConcurrentHashMap
?- Is there way to fix code without replacing map implementation?