How to prevent threads from reading inconsistent data from ConcurrentHashMap?

I'm using a ConcurrentHashMap<String, String> that works as a cache, and where read operations are performed to validate if an element is already in the cache and write operations to add an element to the cache.

So, my question is: what are the best practices to always read the most recent ConcorrentHashMap values?

I want to ensure data consistency and not have cases like:

  1. With the map.get("key") method, the first thread validates that this key does not yet exist in the map, then it does the map.put("value")
  2. The second thread reads the data before the first thread puts the element on the map, leading to inconsistent data.

Code example:

Optional<String> cacheValue = Optional.ofNullable(cachedMap.get("key"));

if (cacheValue.isPresent()) {
    // Perform actions

} else {
    cachedMap.putIfAbsent("key", "value");
    // Perform actions
}

How can I ensure that my ConcurrentHashMap is synchronized and doesn't retrieve inconsistent data?

Should I perform these map operations inside a synchronized block?


You probably need to do it this way:

if (cachedMap.putIfAbsent("key", "value") == null) {
    // Perform actions "IS NOT PRESENT" 
} else {
    // Perform actions "IS PRESENT"
}

Doing it in two checks is obviously not atomic, so if you're having problems with the wrong values getting put in the cache, then that's likely your problem.