Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Executors, atomics and concurrent collections

By the end of this chapter, you'll be able to

  • Submit tasks to an ExecutorService and get their results with Future
  • Explain a data race and recognise one
  • Share a counter with AtomicInteger and a table with ConcurrentHashMap
  • Close an executor properly with try-with-resources

Tasks rather than threads

Creating threads by hand (new Thread(…)) is rarely a good idea. An ExecutorService manages a group of threads (a pool): you submit tasks to it, and it distributes them. submit returns a Future, a promise of a result that get() waits for.

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

int countVowels(String text) {
    int n = 0;
    for (char c : text.toLowerCase().toCharArray()) {
        if ("aeiouy".indexOf(c) >= 0) {
            n++;
        }
    }
    return n;
}

void main() throws Exception {
    List<String> texts = List.of("The Niger river crosses four countries", "Mount Fuji overlooks Tokyo", "The Andes mountain range", "The Atacama desert");

    try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
        List<Future<Integer>> results = new ArrayList<>();
        for (String t : texts) {
            results.add(pool.submit(() -> countVowels(t)));
        }
        int total = 0;
        for (Future<Integer> f : results) {
            total += f.get();
        }
        IO.println("Vowels: " + total);
    }

    AtomicInteger counter = new AtomicInteger();
    Map<String, Integer> words = new ConcurrentHashMap<>();
    try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
        for (String t : texts) {
            pool.submit(() -> {
                for (String w : t.toLowerCase().split(" ")) {
                    counter.incrementAndGet();
                    words.merge(w, 1, Integer::sum);
                }
            });
        }
    }
    IO.println("Words: " + counter.get() + ", \"the\": " + words.get("the") + " times");
}
Vowels: 40
Words: 17, "the": 3 times
  • Executors.newFixedThreadPool(4) creates a pool of 4 threads. The 4 texts are analysed in parallel.
  • f.get() blocks until the task is finished. If the task threw an exception, get() throws an ExecutionException that wraps it: the cause is in getCause().
  • Since Java 19, ExecutorService is AutoCloseable: at the end of the try, close() waits for all tasks to finish then shuts the pool down. That's why the second display sees all 17 words.
  • The counter and the table are modified by 4 threads at once: they must be thread-safe.

The data race

counter++ looks atomic, but it's three operations: read the value, add 1, write the result. If two threads read the same value before one of them writes, an increment is lost. This is a data race.

incrementAndGet does the read, compute and write as a single indivisible operation: nothing is lost.

Step 6 of 6
Text description of the animation
  1. At the start, the counter is 41.
  2. Thread A reads 41…
  3. …and, before A writes, B also reads 41.
  4. A computes 41 + 1 and writes 42.
  5. B also computes 41 + 1 and writes 42: two increments, only one counted.
  6. incrementAndGet does the read, compute and write as a single indivisible operation: nothing is lost.

The safe tools in java.util.concurrent:

NeedTool
a shared counter or numberAtomicInteger, AtomicLong, LongAdder (very high contention)
a shared tableConcurrentHashMap, with merge or compute to read and modify in one go
a queue between producers and consumersArrayBlockingQueue, LinkedBlockingQueue
protecting several related variablesa synchronized block or a ReentrantLock

The best tool is often to share nothing: each task returns its result (like countVowels), and you combine them at the end.

Your turn

Worked exercise

Solved exercise: a parallel sum

Compute the sum of the squares of the integers from 1 to 2,000,000, as a long, by splitting the range into 4 slices processed by a pool of 4 threads. Each task returns the sum of its slice; no variable may be shared. Check the result with the formula n(n + 1)(2n + 1) / 6.

Hint 1
Slice k (from 0 to 3) goes from k * 500_000 + 1 to (k + 1) * 500_000. Compute these bounds in local variables before using them in the lambda.
Hint 2
The formula overflows a long if you multiply everything before dividing: divide by 6 at the end with BigInteger, or compute in an order that avoids overflow.
Show the solution and common mistakes
import java.math.BigInteger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

long sumOfSquares(long from, long to) {
    long s = 0;
    for (long i = from; i <= to; i++) {
        s += i * i;
    }
    return s;
}

void main() throws Exception {
    long n = 2_000_000;
    long total = 0;
    try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
        List<Future<Long>> parts = new ArrayList<>();
        for (int k = 0; k < 4; k++) {
            long from = k * (n / 4) + 1;
            long to = (k + 1) * (n / 4);
            parts.add(pool.submit(() -> sumOfSquares(from, to)));
        }
        for (Future<Long> p : parts) {
            total += p.get();
        }
    }
    BigInteger bn = BigInteger.valueOf(n);
    BigInteger expected = bn.multiply(bn.add(BigInteger.ONE)).multiply(bn.multiply(BigInteger.TWO).add(BigInteger.ONE)).divide(BigInteger.valueOf(6));
    IO.println(total);
    IO.println("correct? " + expected.equals(BigInteger.valueOf(total)));
}
2666668666667000000
correct? true

Each task works on its own variables and returns its result: there's nothing to protect. It's the simplest and fastest model.

Common mistakes:

  • Accumulating into a shared long total modified from the lambdas: the compiler refuses (a captured variable must be effectively final). And a long[1] array to get around the rule creates exactly this chapter's data race.
  • Computing i * i as an int: from 46,341 onwards, the square exceeds an int's capacity and turns negative, without any error.

Summary

  1. 1An ExecutorService runs tasks on a pool of threads; submit returns a Future.
  2. 2Closed by try-with-resources, the executor waits for all its tasks to finish.
  3. 3counter++ shared between threads loses increments: it's a data race.
  4. 4AtomicInteger and ConcurrentHashMap (with merge) are thread-safe.
  5. 5The safest: share nothing, have each task return a result and combine at the end.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.