Skip to main content
ConcurrentHashMap · Topic 4 of 6

Bulk operations

Definition​

ConcurrentHashMap has bulk methods that can run in parallel: forEach, search and reduce. You give a parallelism threshold: the map only splits the work across threads when it is bigger than that number.

Example code​

Totalling and searching a map in parallel

import java.util.concurrent.ConcurrentHashMap;

class Demo {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> sales = new ConcurrentHashMap<>();
sales.put("north", 120);
sales.put("south", 80);
sales.put("east", 200);
sales.put("west", 50);

long threshold = 1; // 1 = use as much parallelism as possible

int total = sales.reduceValues(threshold, Integer::sum); // combine all values
System.out.println("total: " + total);

String bigRegion = sales.search(threshold, (region, amount) -> amount > 150 ? region : null);
System.out.println("over 150: " + bigRegion);

long count = sales.reduceValuesToLong(threshold, v -> 1L, 0L, Long::sum);
System.out.println("regions: " + count);
}
}

// Output:
// total: 450
// over 150: east
// regions: 4

Finished this page? Track your progress (saved only in your browser).