Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet185/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   181   182   183   184   185   186   187   188   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Concurrently updating a map is difficult because it involves two operations: a check- 
then- act type of operation. First, the map must be checked to see whether an entry 
already exists in it. If the entry doesn’t exist, you can put the key and the value into the 
map. On the other hand, if the key exists, the value for the key is retrieved. To do so, we 
use the ConcurrentMap’s putIfAbsent atomic operation. This ensures that the key was 
present, so the value is not overwritten, or the key was not present, so the value is set. 
For the JDK implementations of ConcurrentMap, the putIfAbsent() method returns 
null if there was no value for the key or returns the current value if the key has a value. 
By asserting that the putIfAbsent() method 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 example, 
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, 
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.
Note the following code snippet.
keyPresent = concurrentMap.containsKey(randomInt);
if (!keyPresent) {
concurrentMap.putIfAbsent(randomInt, "Thread # " + i + " has 
made it!");
}
Chapter 10 ConCurrenCy


359
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 
execute the putIfAbsent() operation.
If you are accessing the map’s values from different threads, you should make sure 
that the values are thread-safe. This is most evident when using collections as values 
because they could be accessed from different threads. Ensuring that the main map 
is thread-safe prevent concurrent modifications to the map. However, once you gain 
access to the map’s values, you must exercise good concurrency practices around the 
map’s values.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   181   182   183   184   185   186   187   188   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling