Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
Update a Java ConcurrentHashMap atomically with compute, merge and computeIfAbsent, run parallel search, forEach and reduce bulk operations, build concurrent sets, use copy-on-write lists, parallelSort, parallelSetAll and parallelPrefix, and compare synchronization wrappers.
kvi5hnuCode Sprout team member12 min readOn this page
ConcurrentHashMap is the workhorse of concurrent Java. It's a hash map that many threads can read and update at once without corrupting it and without one global lock. To use it correctly, though, you need its atomic update methods, because a sequence of get and put calls is still a race. This article covers those methods, the parallel bulk operations, concurrent set views, copy-on-write collections, the parallel array algorithms in Arrays, and the older synchronization wrappers.
Atomic update of map entries
Suppose several threads count word frequencies in a shared ConcurrentHashMap<String, Long>. This looks reasonable, but it is wrong:
Long oldValue = map.get(word);
Long newValue = oldValue == null ? 1 : oldValue + 1;
map.put(word, newValue); // ERROR: another thread may have updated the count in between
Two threads can read the same old count, and one increment is lost.
The old ways
In early Java you looped with replace(key, oldValue, newValue), which succeeds only if no other thread has changed the value in the meantime, and you used putIfAbsent for the first insertion:
do {
oldValue = map.get(word);
newValue = oldValue == null ? 1 : oldValue + 1;
} while (oldValue == null ? map.putIfAbsent(word, newValue) != null
: !map.replace(word, oldValue, newValue));
Another approach was a map of AtomicLongs, using map.putIfAbsent(word, new AtomicLong()) and then map.get(word).incrementAndGet(). That works, but it constructs a throwaway AtomicLong on every single increment.
compute, computeIfAbsent, computeIfPresent and merge
Modern Java does the whole read-modify-write atomically for you. compute takes the key and a function. The function receives the key and the current value, or null if there is none, and returns the new value:
map.compute(word, (k, v) -> v == null ? 1 : v + 1);
computeIfPresent runs the function only when a value exists, and computeIfAbsent only when it doesn't. The latter is perfect for a map of LongAdder counters, because the LongAdder is created only when a key is new:
map.computeIfAbsent(word, k -> new LongAdder()).increment();
Most concise of all is merge. It takes an initial value for absent keys and a function that combines the existing value with the given one. Unlike compute, its function doesn't see the key:
map.merge(word, 1L, (existingValue, newValue) -> existingValue + newValue);
map.merge(word, 1L, Long::sum); // same thing
Rules for these methods:
- If the function returns
null, the entry is removed. ConcurrentHashMapdoesn't allownullkeys or values, because many methods usenullto mean "absent".- Keep the function short and side-effect free. While it runs, other updates to the same part of the map may block. The function must never modify the map itself. A nested update can deadlock, loop forever, or throw
IllegalStateException: Recursive update, depending on where the keys hash.
A classic example walks a directory tree, submits one task per .java file to an executor, and lets every task call map.merge(word, 1L, Long::sum). After executor.close() the map holds the word counts. The demo does the same with three lines of text and four tasks.
Bulk operations
ConcurrentHashMap offers bulk operations that traverse the map, in parallel if you like, even while other threads modify it. They don't freeze a snapshot. Unless you know nobody is modifying the map, treat the result as an approximation. There are three kinds:
searchapplies a function to each key and/or value until it returns a non-nullresult, and returns that result.reducecombines all keys and/or values with an accumulation function.forEachapplies a function to all keys and/or values.
Each comes in four variants: operationKeys, operationValues, operation (keys and values together, with a BiFunction), and operationEntries (Map.Entry objects).
Every bulk operation takes a parallelism threshold as its first argument. If the map has more elements than the threshold, the operation runs in parallel in the common fork-join pool. Use Long.MAX_VALUE to force a single thread, or 1 to allow maximum parallelism.
String result = map.search(threshold, (k, v) -> v > 1000 ? k : null);
result is the first match found, or null if the function returned null for everything. In parallel mode, "first" means any match.
forEach has a plain form and a form with a transformer whose result is passed to the consumer. A transformer that returns null acts as a filter:
map.forEach(threshold, (k, v) -> System.out.println(k + " -> " + v));
map.forEach(threshold,
(k, v) -> v > 1000 ? k + " -> " + v : null, // transformer and filter
System.out::println); // consumer; nulls are skipped
reduce combines values with an accumulator, optionally after a transformer:
Long sum = map.reduceValues(threshold, Long::sum);
Integer maxLength = map.reduceKeys(threshold, String::length, Integer::max);
Long count = map.reduceValues(threshold, v -> v > 1000 ? 1L : null, Long::sum);
If the map is empty, or the transformer filtered everything out, reduce returns null. With exactly one element, its transformed value is returned without calling the accumulator.
There are primitive specializations with the suffixes ToInt, ToLong and ToDouble. You supply a transformer to the primitive type, a default value and a primitive accumulator:
long sum = map.reduceValuesToLong(threshold,
Long::longValue, // transformer to primitive
0, // default for an empty map
Long::sum); // primitive accumulator
Bulk operations work only on ConcurrentHashMap. For general maps, streams over entrySet() with .parallel() do similar work.
Concurrent set views
There is no ConcurrentHashSet class, and you shouldn't build your own. Use the static newKeySet method, which returns a Set<K> backed by a ConcurrentHashMap<K, Boolean> whose values are all Boolean.TRUE:
Set<String> words = ConcurrentHashMap.newKeySet();
An existing map's keySet() is a live, mutable view. Removing a key from the set removes the entry from the map. Adding makes no sense, because there would be no value. A second overload, keySet(defaultValue), allows adding and uses the default as the value:
Set<String> words = map.keySet(1L);
words.add("Java"); // if absent, "Java" now maps to 1
Collections.newSetFromMap(new ConcurrentHashMap<>()) also works, but newKeySet is simpler and slightly more efficient. For a sorted concurrent set, use ConcurrentSkipListSet (article 100).
Copy-on-write arrays
CopyOnWriteArrayList and CopyOnWriteArraySet are thread-safe because every mutator copies the underlying array. An iterator holds a reference to the array that existed when it was created. Later mutations build a new array and swap it in, so the old iterator keeps a consistent but possibly outdated view. It needs no locking and never throws ConcurrentModificationException.

That is a great trade-off when iteration vastly outnumbers mutation. The classic example is a list of event listeners that are registered rarely and notified constantly. With frequent writes, every write copies the whole array, which is O(n). In that case a synchronized ArrayList is usually faster. Iterators of these classes don't support remove, and CopyOnWriteArraySet keeps insertion order with an O(n) contains.
Parallel array algorithms
The Arrays class has several parallelized operations, which use the common fork-join pool for large arrays.
Arrays.parallelSort sorts primitive arrays or object arrays, optionally with a Comparator and a range:
String[] words = contents.split("\\PL+"); // split on non-letters
Arrays.parallelSort(words);
Arrays.parallelSort(words, Comparator.comparing(String::length));
Arrays.parallelSort(values, values.length / 2, values.length); // sort the upper half
The word parallel in the name is a warning. Since the work is split among threads, your comparator must not have side effects. For small arrays (below 8,192 elements, an implementation detail) it falls back to the sequential sort.
Arrays.parallelSetAll fills an array from a function of the index:
Arrays.parallelSetAll(values, i -> i % 10); // 0 1 2 ... 9 0 1 2 ...
There are versions for all primitive arrays and for object arrays.
Arrays.parallelPrefix replaces each element with the accumulation of all elements up to it, for an associative operation. For [1, 2, 3, 4, …] and multiplication, the result is [1, 1×2, 1×2×3, 1×2×3×4, …]. With addition, you get running totals.
It's surprising that this can be parallelized at all, since each value depends on the previous one. The trick works in rounds. First, combine neighbors pairwise, giving [1, 1×2, 3, 3×4, 5, 5×6, 7, 7×8]. Each pair is independent, so all of them can be done at once. Next, combine each element with the results one or two positions below, which yields complete prefixes for blocks of four, again in parallel. After about log n rounds the whole array is done. That's a win over the linear loop when enough processors are available. GPUs and other parallel hardware use this scan algorithm all the time.
Older thread-safe collections
Vector and Hashtable have been thread-safe since Java 1.0. They're now considered obsolete, replaced by the unsynchronized ArrayList and HashMap (article 91). Instead, any collection can be made thread-safe with a synchronization wrapper:
List<E> syncList = Collections.synchronizedList(new ArrayList<E>());
Map<K, V> syncMap = Collections.synchronizedMap(new HashMap<K, V>());
Each method of the wrapper locks the wrapper object. Two rules apply:
- Never use the original collection after wrapping it. The easiest way to ensure that is to keep no reference to it, as above.
- Lock the wrapper while iterating with client-side locking. A for-each loop uses an iterator, so it needs this too:
synchronized (syncMap) {
Iterator<K> iter = syncMap.keySet().iterator();
while (iter.hasNext()) ...
}
Without the lock, another thread's modification makes the iterator fail with ConcurrentModificationException. With the lock, no modification can happen, and the failure detection stays reliable.
Recommendation. Prefer the java.util.concurrent collections. ConcurrentHashMap lets threads that touch different bins work without blocking each other at all, whereas a synchronized map serializes everything. The exception is a list that is mutated often. There, a synchronized ArrayList can outperform CopyOnWriteArrayList.
A complete example
The demo counts words with merge from four tasks. It tries every atomic update style (the replace loop, compute, computeIfPresent, merge returning null, and computeIfAbsent with LongAdder) and runs search, forEach and several reduce operations, including the default-value trap. It then uses newKeySet and keySet(1L), shows a copy-on-write iterator's snapshot, runs the parallel array algorithms, and iterates a synchronized list under a client-side lock.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Solution {
static final String TEXT = """
the quick brown fox jumps over the lazy dog the dog sleeps
a fox is quick and a dog is lazy so the fox wins the race
concurrency is hard but the right collection makes it easy
""";
public static void main(String[] args) throws Exception {
String[] words = TEXT.trim().split("\\PL+");
System.out.println("-- counting words from 4 threads with merge --");
var counts = new ConcurrentHashMap<String, Long>();
try (var pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++) {
int start = t;
pool.submit(() -> {
for (int i = start; i < words.length; i += 4)
counts.merge(words[i], 1L, Long::sum);
});
}
} // close() waits for all tasks
System.out.println(" " + words.length + " words, " + counts.size() + " distinct; the=" + counts.get("the")
+ ", fox=" + counts.get("fox") + ", dog=" + counts.get("dog"));
System.out.println("-- other atomic update styles --");
var m = new ConcurrentHashMap<String, Long>();
// old style: retry replace until no other thread interfered
for (int i = 0; i < 3; i++) {
Long oldValue, newValue;
do {
oldValue = m.get("java");
newValue = oldValue == null ? 1 : oldValue + 1;
} while (oldValue == null ? m.putIfAbsent("java", newValue) != null : !m.replace("java", oldValue, newValue));
}
System.out.println(" replace loop: java=" + m.get("java"));
m.compute("java", (k, v) -> v == null ? 1 : v + 1);
m.compute("kotlin", (k, v) -> v == null ? 1 : v + 1);
System.out.println(" compute: " + new TreeMap<>(m));
m.computeIfPresent("kotlin", (k, v) -> v + 10);
m.computeIfPresent("scala", (k, v) -> v + 10);
System.out.println(" computeIfPresent: " + new TreeMap<>(m));
m.merge("kotlin", 1L, (oldV, one) -> null); // returning null removes the entry
System.out.println(" merge returning null removes kotlin: " + new TreeMap<>(m));
var adders = new ConcurrentHashMap<String, LongAdder>();
for (String w : words) adders.computeIfAbsent(w, k -> new LongAdder()).increment();
System.out.println(" computeIfAbsent + LongAdder: the=" + adders.get("the").sum());
try { m.put("nothing", null); } catch (NullPointerException e) { System.out.println(" null values: NullPointerException"); }
System.out.println("-- bulk operations --");
long threshold = 1; // parallelize whenever possible
String firstBig = counts.search(Long.MAX_VALUE, (k, v) -> v >= 6 ? k : null);
System.out.println(" search for a word occurring >= 6 times: " + firstBig);
var printed = new ConcurrentSkipListSet<String>();
counts.forEach(threshold, (k, v) -> v >= 3 ? k + "->" + v : null, printed::add);
System.out.println(" forEach with filtering transformer: " + printed);
Long total = counts.reduceValues(threshold, Long::sum);
Integer longest = counts.reduceKeys(threshold, String::length, Integer::max);
Long frequent = counts.reduceValues(threshold, v -> v >= 2 ? 1L : null, Long::sum);
long sum2 = counts.reduceValuesToLong(threshold, Long::longValue, 0, Long::sum);
System.out.println(" reduceValues sum = " + total + ", longest key = " + longest
+ ", words with count >= 2: " + frequent + ", reduceValuesToLong = " + sum2);
System.out.println(" reduce over an empty selection: " + counts.reduceValues(threshold, v -> v > 100 ? v : null, Long::sum));
var single = new ConcurrentHashMap<>(Map.of("x", 5L));
System.out.println(" one element, ToLong with default 10: " + single.reduceValuesToLong(threshold, Long::longValue, 10, Long::sum)
+ " (the default is combined, so it must be the neutral element)");
System.out.println("-- concurrent set views --");
Set<String> seen = ConcurrentHashMap.newKeySet();
Collections.addAll(seen, words);
System.out.println(" newKeySet size: " + seen.size() + ", contains fox: " + seen.contains("fox"));
var langs = new ConcurrentHashMap<String, Long>(Map.of("java", 3L));
Set<String> withDefault = langs.keySet(1L);
withDefault.add("go");
withDefault.add("java"); // already present: value unchanged
System.out.println(" keySet(1L).add: " + new TreeMap<>(langs));
langs.keySet().remove("go");
System.out.println(" removing from the key set removes the entry: " + langs);
System.out.println("-- copy-on-write --");
var listeners = new CopyOnWriteArrayList<>(List.of("L1", "L2", "L3"));
var visited = new ArrayList<String>();
for (String l : listeners) {
visited.add(l);
if (l.equals("L1")) { listeners.add("L4"); listeners.remove("L3"); }
}
System.out.println(" iterator saw snapshot " + visited + ", list is now " + listeners);
var cows = new CopyOnWriteArraySet<>(List.of("b", "a", "b"));
System.out.println(" CopyOnWriteArraySet keeps insertion order: " + cows);
System.out.println("-- parallel array algorithms --");
String[] sorted = words.clone();
Arrays.parallelSort(sorted);
System.out.println(" parallelSort: " + String.join(" ", Arrays.copyOf(sorted, 8)) + " ...");
String[] byLength = {"pear", "fig", "banana", "kiwi", "apple"};
Arrays.parallelSort(byLength, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(" with comparator: " + Arrays.toString(byLength));
int[] part = {9, 8, 7, 6, 5, 4, 3, 2, 1};
Arrays.parallelSort(part, 3, 9);
System.out.println(" range [3, 9) only: " + Arrays.toString(part));
int[] values = new int[12];
Arrays.parallelSetAll(values, i -> i % 10);
System.out.println(" parallelSetAll(i -> i % 10): " + Arrays.toString(values));
long[] prefix = {1, 2, 3, 4, 5, 6, 7, 8};
Arrays.parallelPrefix(prefix, (x, y) -> x * y);
System.out.println(" parallelPrefix with *: " + Arrays.toString(prefix));
int[] running = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.parallelPrefix(running, Integer::sum);
System.out.println(" parallelPrefix with +: " + Arrays.toString(running));
System.out.println("-- synchronization wrappers --");
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
try (var pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++)
pool.submit(() -> { for (int i = 0; i < 1000; i++) syncList.add(i); });
}
long sumList;
synchronized (syncList) { // client-side lock required for iteration
sumList = 0;
for (int x : syncList) sumList += x;
}
System.out.println(" synchronizedList size " + syncList.size() + ", sum " + sumList);
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());
syncMap.put("a", 1);
System.out.println(" synchronizedMap: " + syncMap);
}
}
-- counting words from 4 threads with merge --
37 words, 23 distinct; the=6, fox=3, dog=3
-- other atomic update styles --
replace loop: java=3
compute: {java=4, kotlin=1}
computeIfPresent: {java=4, kotlin=11}
merge returning null removes kotlin: {java=4}
computeIfAbsent + LongAdder: the=6
null values: NullPointerException
-- bulk operations --
search for a word occurring >= 6 times: the
forEach with filtering transformer: [dog->3, fox->3, is->3, the->6]
reduceValues sum = 37, longest key = 11, words with count >= 2: 7, reduceValuesToLong = 37
reduce over an empty selection: null
one element, ToLong with default 10: 15 (the default is combined, so it must be the neutral element)
-- concurrent set views --
newKeySet size: 23, contains fox: true
keySet(1L).add: {go=1, java=3}
removing from the key set removes the entry: {java=3}
-- copy-on-write --
iterator saw snapshot [L1, L2, L3], list is now [L1, L2, L4]
CopyOnWriteArraySet keeps insertion order: [b, a]
-- parallel array algorithms --
parallelSort: a a and brown but collection concurrency dog ...
with comparator: [fig, kiwi, pear, apple, banana]
range [3, 9) only: [9, 8, 7, 1, 2, 3, 4, 5, 6]
parallelSetAll(i -> i % 10): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
parallelPrefix with *: [1, 2, 6, 24, 120, 720, 5040, 40320]
parallelPrefix with +: [3, 4, 8, 9, 14, 23, 25, 31]
-- synchronization wrappers --
synchronizedList size 4000, sum 1998000
synchronizedMap: {a=1}
Common questions
What is the best way to count with a ConcurrentHashMap?
map.merge(key, 1L, Long::sum). It updates the entry atomically. Under very heavy contention on a few keys, a ConcurrentHashMap<String, LongAdder> with computeIfAbsent(key, k -> new LongAdder()).increment() scales even better.
Why does computeIfAbsent throw IllegalStateException: Recursive update?
The function you passed modifies the same map, for example by calling computeIfAbsent again for another key. That is not allowed. Compute the value first, outside the map operation, or restructure the code so the function doesn't touch the map.
How do I get a concurrent Set?
Call ConcurrentHashMap.newKeySet(). For a sorted concurrent set, use ConcurrentSkipListSet. There is no ConcurrentHashSet class.
When should I use CopyOnWriteArrayList?
When the list is read and iterated far more often than it's changed, such as a list of listeners. Every write copies the entire array, so it's a poor choice for lists that change often.
Is Arrays.parallelSort always faster than Arrays.sort?
No. For small arrays it falls back to the sequential sort anyway, and the parallel version uses the common fork-join pool, which other code may need too. It pays off for large arrays on machines with several cores. Measure before switching.
API reference
java.util.concurrent.ConcurrentHashMap<K, V>
| Method | Description |
|---|---|
V compute(K key, BiFunction<? super K, ? super V, ? extends V> f) | atomically computes the new value from key and old value (null if absent); null result removes the entry |
V computeIfAbsent(K key, Function<? super K, ? extends V> f) | computes and stores a value only if the key is absent; returns the current value |
V computeIfPresent(K key, BiFunction<...> f) | recomputes only if the key is present |
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> f) | stores value if absent, else combines the old value and value |
V putIfAbsent(K key, V value), boolean replace(K key, V oldValue, V newValue) | older atomic primitives |
U search(long threshold, BiFunction<? super K, ? super V, ? extends U> f) (+ searchKeys, searchValues, searchEntries) | first non-null result |
void forEach(long threshold, BiConsumer<...> action); forEach(threshold, transformer, action) | applies an action, optionally after a filtering transformer |
V reduceValues(long threshold, BiFunction<...> reducer); reduceKeys(threshold, transformer, reducer) | combines; null if nothing remains |
long reduceValuesToLong(long threshold, ToLongFunction<...> t, long basis, LongBinaryOperator r) (+ ToInt, ToDouble) | primitive reduction; basis must be neutral |
static <K> KeySetView<K, Boolean> newKeySet(), KeySetView<K, V> keySet(V mappedValue) | concurrent set; key set that can add with a default value |
Copy-on-write, java.util.Arrays and java.util.Collections
| Method | Description |
|---|---|
CopyOnWriteArrayList(), CopyOnWriteArraySet() | collections whose mutators copy the array; snapshot iterators |
static void parallelSort(T[] a, Comparator<? super T> c), parallelSort(a, fromIndex, toIndex) | parallel sort of all or part of an array (primitive overloads too) |
static void parallelSetAll(T[] a, IntFunction<? extends T> generator) | sets each element from its index (primitive overloads too) |
static void parallelPrefix(T[] a, BinaryOperator<T> op) | replaces each element with the prefix accumulation under an associative op |
synchronizedCollection, synchronizedList, synchronizedSet, synchronizedSortedSet, synchronizedMap, synchronizedSortedMap | views whose methods lock the wrapper (synchronizedNavigableSet/Map since Java 8) |
Summary
- A concurrent map protects its structure, not your call sequences. Use
compute,computeIfAbsent,computeIfPresentormergefor read-modify-write. Anullresult removes the entry, and the function must be short and must not touch the map. computeIfAbsent(k, x -> new LongAdder()).increment()andmerge(k, 1L, Long::sum)are the idiomatic concurrent counters.- Bulk
search,forEachandreduceoperations take a parallelism threshold, use transformers as filters, and return approximate results while the map changes. Primitive reductions need a neutral default. ConcurrentHashMap.newKeySet()is the concurrent hash set, andkeySet(default)lets you add keys.- Copy-on-write collections suit read-mostly data such as listener lists.
Arrays.parallelSort,parallelSetAllandparallelPrefixparallelize array work. - Synchronization wrappers lock everything and need client-side locking for iteration. Prefer
java.util.concurrentcollections.
Practice Questions
Why is "map.put(word, map.getOrDefault(word, 0L) + 1)" wrong on a ConcurrentHashMap, and what should you write?
Another thread can update the count between the get and the put, so increments get lost. The map's structure stays intact, but the sequence isn't atomic. Write map.merge(word, 1L, Long::sum) or map.compute(word, (k, v) -> v == null ? 1 : v + 1).
What advantage does computeIfAbsent(k, x -> new LongAdder()) have over putIfAbsent(k, new LongAdder())?
putIfAbsent evaluates its argument first, so it constructs a new LongAdder on every call and then discards it when the key already exists. computeIfAbsent calls the function only when the key is absent.
What does a parallelism threshold of 1 mean in map.reduceValues(1, Long::sum)? And Long.MAX_VALUE?
A threshold of 1 means the operation is parallelized whenever the map has more than one element, which allows maximum parallelism. Long.MAX_VALUE means the map is never "big enough", so the operation runs in the calling thread.
When is CopyOnWriteArrayList a good choice, and when a bad one?
It's good when iteration is far more frequent than modification, as with listener lists, because iterators need no locks and never throw ConcurrentModificationException. It's bad when writes are frequent or the list is large, because every write copies the entire array.
Why must you lock a synchronizedList while iterating over it?
The wrapper locks only individual method calls. An iteration is many calls, so another thread could modify the list in the middle and cause ConcurrentModificationException or inconsistent results. Holding the wrapper's lock for the whole loop blocks other threads' modifications.
Previous: Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
Next: Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
Related reading
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate
- Java Processes and ProcessBuilder: Running and Managing External Programs

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.