Java Reference
In-Depth Information
od returns null , you are assured that the operation was successful and that a new
entry in the map has been created.
There are cases when putIfAbsent() might not be efficient to execute. For ex-
ample, if the result is a large database query, executing the database query all the time
and then invoking putIfAbsent() will not be efficient. In this kind of scenario, you
could first call the map's containsKey() method to ensure that the key is not
present. If it's not present, then call the putIfAbsent() with the expensive database
query. There might be a chance that the putIfAbsent() didn't put the entry, but
this type of check reduces the number of potentially expensive value creation.
See the following code snippet:
keyPresent = concurrentMap.containsKey(randomInt);
if (!keyPresent) {
concurrentMap.putIfAbsent(randomInt,
"Thread # " + i + " has made it!");
}
In this code, the first operation is to check whether the key is already in the map. If
it is, it doesn't execute the putIfAbsent() operation. If the key is not present, we
can proceed to execute the putIfAbsent() operation.
If you are accessing the values of the map from different threads, you should make
sure that the values are thread-safe. This is most evident when using collections as val-
ues because they then could be accessed from different threads. Ensuring that the main
map is thread-safe will prevent concurrent modifications to the map. However, once
you gain access to the values of the map, you must exercise good concurrency practices
around the values of the map.
Note ConcurrentMaps do not allow null keys, which is different from its
non-thread safe cousin HashMap (which does allow null keys).
10-4. Iterating Through a Changing Col-
lection
Problem
Search WWH ::




Custom Search