Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
Solution
Use ConcurrentMap 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 public static void main(String[] args) { Recipe10_2 recipe = new Recipe10_2(); recipe.startProcess(); } private void startProcess() { ConcurrentMap 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 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 |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling