Motivation
Concurrency Utilities in java.util.concurrent
Utility categories:
Competing Collections
Features:
Map<String, String> map = new ConcurrentHashMap<>(); String result = map.putIfAbsent("key", "value"); if (result == null) { System.out.println("Valor inserido."); } else { System.out.println("Chave já existente com valor: " + result); }
Benefits:
Synchronizers
Purpose: Coordination between threads.
Example of common synchronizers:
Practical Example: Concurrent Timing with CountDownLatch
Objective: Measure the execution time of several threads concurrently.
Implementation:
public static long time(Executor executor, int concurrency, Runnable action) throws InterruptedException { CountDownLatch ready = new CountDownLatch(concurrency); CountDownLatch start = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(concurrency); for (int i = 0; i < concurrency; i++) { executor.execute(() -> { try { ready.countDown(); // Indica que está pronto start.await(); // Aguarda o sinal de início action.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { done.countDown(); // Indica que terminou } }); } ready.await(); // Aguarda todas as threads ficarem prontas long startTime = System.nanoTime(); start.countDown(); // Dispara o sinal de início done.await(); // Aguarda todas as threads finalizarem return System.nanoTime() - startTime; }
Notes:
Current practice with wait and notify
Only needed for legacy code maintenance.
Main rules:
synchronized (lock) { while (!condition) { lock.wait(); } }
Conclusion
Examples from the book
The above is the detailed content of Item Prefer concurrency utilities to wait and notify. For more information, please follow other related articles on the PHP Chinese website!