Video in progress
What do ConcurrentHashMap's bulk methods like forEach, search and reduce give you, and how does the parallelismThreshold parameter work?
Since Java 8, ConcurrentHashMap has methods that traverse the Map without locks and, if needed, in parallel. parallelismThreshold is an estimated element-count limit: if the Map is smaller, the work runs on one thread; if larger, it is split and run in ForkJoinPool.commonPool().
📖 Answer
ConcurrentHashMap<String, Long> balances = loadBalances();
// with more than 10,000 entries, this is computed in parallel
long total = balances.reduceValuesToLong(10_000, Long::longValue, 0L, Long::sum);
// returns the first non-null result, and the rest of the search is stopped
String debtor = balances.search(10_000, (k, v) -> v < 0 ? k : null);
// Long.MAX_VALUE: always on a single thread
balances.forEach(Long.MAX_VALUE, (k, v) -> log.info("{}={}", k, v));
1 means maximum parallelism, and Long.MAX_VALUE means no parallelism at all.
These methods have the same semantics as weakly consistent iteration: while other threads are writing, the result of reduce may not match the state at any single moment. That is enough for monitoring or rough statistics, but not for balance calculations.
What to watch out for:
- the parallel variant runs on the shared
commonPool. If you give it a slow function (DB, HTTP), parallel streams andCompletableFutures that use the same pool end up waiting too; - in
search,nullmeans "not found", so you can't return null as a result; - don't modify this same Map inside the function.
On small maps (a few thousand entries) the parallel version gives no benefit, because the cost of splitting is bigger than the work itself. I choose the threshold by measuring, and if I haven't measured, I use Long.MAX_VALUE.
Sign up to mark studied questions and save your progress.