I have a question regarding synchronisation. I have one single instance of:
`
@Service
public class MyService {
//if singleton - should this map be static?
private static Map<String, String> cache = new ConcurrentHashMap<String, String>();
public String put(String value) {
if (!cache.containsKey(value)) {
String newValue = someRandomString();
cache.put(value, newValue);
return newValue;
}
return cache.get(value);
}
public String get(String value) {
return cache.entrySet().stream()
.filter(e -> e.getValue().equals(value))
.map(Map.Entry::getKey)
.findFirst().get();
}
}
The question is - how to make proper synchronisation in case of singleton and many threads calling the service. Seems like both methods are affected and sometimes no appropriate data can be calculated/put into map for the same String values. Is ConcurrentHashMap to be replaced by SynchronizedMap? Should I make a synchronized block in both methods?