Concurrent collections and atomics
What you will learn
Concurrent collections offer defined thread-safe operations, and atomic variables offer single-value atomic updates. Choose an operation that matches the invariant: a per-key update can be atomic even when a sequence of updates across multiple keys is not.
- Use atomic operations rather than separate read/write steps.
- Perform an atomic per-key map update.
- Use a bounded blocking queue and explain cross-object invariants.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Count completed tasks
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { AtomicInteger completed = new AtomicInteger(); LongAdder metrics = new LongAdder(); ThreadPoolExecutor workers = pool(2, 2); Runnable job = () -> { for (int i = 0; i < 100; i++) { completed.incrementAndGet(); metrics.increment(); } }; try { Future<?> a = workers.submit(job), b = workers.submit(job); a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS); System.out.println(completed.get()); System.out.println(metrics.sum()); System.out.println(completed.compareAndSet(200, 201)); System.out.println(completed.get()); } finally { stop(workers); } }}Expected output:
200200true201Each increment is atomic for its counter. The LongAdder result is read after both writers finish, not while writes are active.
Atomic variables and counters
AtomicInteger.incrementAndGet changes one value atomically and returns the new value; compareAndSet changes it only if the expected value matches. Separate get and set operations do not implement an atomic increment. A compare-and-set loop must re-read on failure, and update functions may run more than once, so keep them free of external side effects. LongAdder spreads contention across internal cells; sum is not an atomic snapshot during concurrent updates, but after all writers finish it reports their total. Use atomic variables for a single-value invariant, not as a substitute for coordinated changes to several values.
Concurrent maps and collection guarantees
ConcurrentHashMap rejects null keys and values. merge and compute can update one key atomically; keep callbacks short and avoid modifying the same map from them. get followed by put is not a single atomic operation. Iterators are weakly consistent rather than snapshots; size during updates is not a reliable admission check. CopyOnWriteArrayList has snapshot iterators and expensive writes, useful only for suitable read-heavy workloads. Two concurrent map entries representing a transfer require a shared transaction or lock respected by all relevant accessors; a thread-safe map alone cannot preserve their sum during a transfer.
Bounded queues
BlockingQueue.put and take may block until capacity or data becomes available. Timed offer returns false on timeout; timed poll returns null if no item becomes available. Null is not a valid queue element. Use capacity limits, timed operations or cancellation and explicit worker shutdown. A queue does not provide a built-in close protocol; a known finite count, agreed sentinel, or external lifecycle control is required. Do not use size followed by add as a capacity reservation.
Count events per key
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>(); ThreadPoolExecutor workers = pool(2, 2); Runnable job = () -> { for (int i = 0; i < 100; i++) counts.merge("book", 1, Integer::sum); }; try { Future<?> a = workers.submit(job), b = workers.submit(job); a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS); System.out.println(counts.get("book")); System.out.println(counts.computeIfAbsent("pen", key -> 0)); } finally { stop(workers); } }}Expected output:
2000The map coordinates the merge for the same key. The mapping callback initializes an absent key without an external side effect.
Apply queue backpressure
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { BlockingQueue<String> jobs = new ArrayBlockingQueue<>(1); System.out.println(jobs.offer("first", 0, TimeUnit.SECONDS)); System.out.println(jobs.offer("second", 0, TimeUnit.SECONDS)); ThreadPoolExecutor workers = pool(1, 1); try { Future<String> result = workers.submit(() -> jobs.poll(3, TimeUnit.SECONDS)); System.out.println(result.get(3, TimeUnit.SECONDS)); System.out.println(jobs.offer("second", 0, TimeUnit.SECONDS)); System.out.println(jobs.poll(0, TimeUnit.SECONDS)); System.out.println(jobs.poll(0, TimeUnit.SECONDS) == null); } finally { stop(workers); } }}Expected output:
truefalsefirsttruesecondtrueThe full queue refuses the second item without growing; once a worker consumes the first, capacity becomes available. No timing assumption about the worker is needed.
Observe a snapshot iterator
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CopyOnWriteArrayList<String> listeners = new CopyOnWriteArrayList<>(); listeners.add("A"); var snapshot = listeners.iterator(); listeners.add("B"); snapshot.forEachRemaining(System.out::println); System.out.println(listeners); }}Expected output:
A[A, B]The iterator sees the array at creation, not the later addition. Each write copies the backing array; this is not the same iteration guarantee as ConcurrentHashMap.
Common mistakes
Do not treat LongAdder.sum as an exact concurrent quota, concurrent map size as an atomic capacity check, or get plus put as a single atomic operation. Do not infer queue closure from emptiness. Use one explicit lock or transaction for multi-key invariants.
Practice
Use two submitted tasks to add 40 and 60 events to the same map key via merge. Wait for both, print the total, and release the owned pool.
Expected output:
100Compare your answer with the manual practice criteria.
Official reading: ConcurrentHashMap · Concurrency package. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrent collections and atomics — knowledge check
Original concurrency questions. Java 21-compatible scope.
Which operation increments a single AtomicInteger atomically?
When is LongAdder.sum an exact completed-work total in the example?
Which operation combines a value for one map key atomically?
What does timed offer return on a full queue after timeout?
Does a ConcurrentHashMap guarantee a two-key transfer invariant?