Java 17 Recipes


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

 Solution
Use ConcurrentMap to update map entries. The following example creates 1,000 
threads. Each thread then tries to modify the map at the same time. The main thread 
waits for a second and proceeds to iterate through the map (even when the other threads 
are still modifying the map).
public class Recipe10_2 {
Set updateThreads = new HashSet<>();
public static void main(String[] args) {
Recipe10_2 recipe = new Recipe10_2();
recipe.startProcess();
}
private void startProcess() {
ConcurrentMap concurrentMap = new 
ConcurrentHashMap<>();
for (int i =0;i < 1000;i++) {
startUpdateThread(i, concurrentMap);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
concurrentMap.entrySet().stream().forEach((entry) -> {
System.out.println("Key :"+entry.getKey()+"
Value:"+entry.getValue());
});
Chapter 10 ConCurrenCy


355
updateThreads.stream().forEach((thread) -> {
thread.interrupt();
});
}
Random random = new Random();
private void startUpdateThread(int i, final ConcurrentMapString> concurrentMap) {
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
int randomInt = random.nextInt(20);
concurrentMap.put(randomInt,
UUID.randomUUID().toString());
}
});
thread.setName("Update Thread "+i);
updateThreads.add(thread);
thread.start();
}
}
The following is the output.
Key :0 Value:d4476b69-a28f-44d6-b1ce-f47128ed5a59
Key :1 Value:1f47b9ee-5b01-4ea3-ac2a-b1a2231187ad
Key :2 Value:95322e14-73a5-449e-87e2-d7d0dafdbabd
...
 How It Works
For performing work on a hash table in a concurrent manner, ConcurrentHashMap allows 
multiple threads to modify the hash table concurrently and safely. ConcurrentHashMap 
is a hash table supporting full concurrency for retrievals and adjustable expected 
concurrency for updates. In the example, 1,000 threads make modifications to the map 
over a short period of time. The ConcurrentHashMap iterator, as well as streams that 
are generated on a ConcurrentHashMap, allows safe iteration over its contents. When 
using the ConcurrentMap’s iterator, you do not have to worry about locking the contents 
of the ConcurrentMap while iterating over it.
Chapter 10 ConCurrenCy


356

Download 3.2 Mb.

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




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