I have the following code:
public class Cache {
private final Map map = new ConcurrentHashMap();
public Object get(Object key) {
Object value = map.get(key);
if (value == null) {
value = new SomeObject();
map.put(key, value);
}
return value;
}
}
My question is:
The put
and get
methods of the map are thread safe, but since the whole block in not synchronized – could multiple threads add a the same key twice?
Best Answer
As of Java 8, you can also prevent this addition of duplicate keys with:
The API docs state: