Java 17 Recipes


-3. Inserting a Key into a Map Only If the Key Is


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

10-3. Inserting a Key into a Map Only If the Key Is 
Not Already Present
 Problem
A map within your application is continuously updated, and you need to put a key/value 
pair into it if the key does not exist. Therefore, you need to check for the key’s presence
and you need assurance that some other thread doesn’t insert the same key in the 
meantime.
 Solution
Using the ConcurrentMap.putIfAbsent() method, you can determine whether the map 
was modified atomically. For example, the following code uses this method to check and 
insert in a single step, thus avoiding the concurrency problem.
public class Recipe10_3 {
Set updateThreads = new HashSet<>();
Random random = new Random();
public static void main(String[] args) {
Recipe10_3 recipe = new Recipe10_3();
recipe.startProcess();
}
private void startProcess() {
ConcurrentMap concurrentMap = new 
ConcurrentHashMap<>();
for (int i = 0; i < 100; i++) {
startUpdateThread(i, concurrentMap);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Chapter 10 ConCurrenCy


357
concurrentMap.entrySet().stream().forEach((entry) -> {
System.out.println("Key :" + entry.getKey() + " Value:" + 
entry.getValue());
});
}
private void startUpdateThread(final int i, final 
ConcurrentMap concurrentMap) {
Thread thread = new Thread(() -> {
int randomInt = random.nextInt(20);
String previousEntry = concurrentMap.putIfAbsent(randomInt, 
"Thread # " + i + " has made it!");
if (previousEntry != null) {
System.out.println("Thread # " + i + " tried to update 
it but guess what, we're too late!");
} else {
System.out.println("Thread # " + i + " has made it!");
}
});
thread.start();
}
}
The following is the output.
Thread # 1 has made it!
Thread # 0 has made it!
Thread # 3 has made it!
Thread # 2 has made it!
Thread # 4 has made it!
Thread # 5 has made it!
Thread # 9 has made it!
Thread # 8 tried to update it but guess what, we're too late!
Thread # 10 tried to update it but guess what, we're too late!
Thread # 7 has made it!
Thread # 12 has made it!
Chapter 10 ConCurrenCy


358
Thread # 6 tried to update it but guess what, we're too late!
Thread # 13 tried to update it but guess what, we're too late!
Thread # 11 tried to update it but guess what, we're too late!
When running the program, some of the entries will be successfully inserted, while 
others will not because another thread has already inserted the key. Note that in the 
example, startUpdateThread() accepts a final int i argument. Marking a method 
argument as final ensures that the method cannot change the value of the i variable. If 
the value of i changes inside the method, it is not visible from outside the method.

Download 3.2 Mb.

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




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