Command Palette

Search for a command to run...

Back to the lesson: Topic 13.8 — Concurrent Collections and Atomics
Core Java · Example 2 of 4 Java 9+

Counting words from several threads with ConcurrentHashMap

The map is copied into a TreeMap only to print it in a fixed order.

java.util.concurrent gives you thread-safe building blocks so you rarely need your own locks: atomic variables (AtomicInteger, LongAdder), concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue) and synchronizers (CountDownLatch, Semaphore, CyclicBarrier).

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use a CountDownLatch so main waits for three worker threads, each adding 100 to a shared AtomicInteger.

Explain it without notes

01

How does an AtomicInteger increment without a lock?

02

Why can get-then-put on a ConcurrentHashMap still lose updates, and what should you use?

03

When would you use CountDownLatch, Semaphore and CyclicBarrier?

Counting words from several threads with ConcurrentHashMap Java 9+
Sign in to run this example in your browser.

Expected output

{be=2, do=3, is=1, not=2, or=2, to=3}