Java · Advanced level

Advanced level · Module 2: Modern Java Language and Design · Lesson 4 of 4

Concurrency Fundamentals

Run independent tasks in parallel with executors and CompletableFuture, and avoid race conditions on shared data.

In this lesson you will

  • Run tasks with ExecutorService and CompletableFuture
  • Recognise race conditions and fix them with immutable data, atomics or synchronization

Key concepts

threadExecutorServiceCompletableFuturerace conditionAtomicInteger

The lesson

Concurrency lets a program do several things at once, such as calling three APIs in parallel. Create threads through an ExecutorService rather than new Thread(): the executor reuses a pool of threads and must be shut down when work is finished.

CompletableFuture.supplyAsync(() -> fetchRates()) starts work in the background; thenApply transforms the result and join waits for it. Combining futures lets you wait for several independent calls at once.

When two threads update the same variable, updates can be lost — a race condition. Prefer immutable data and collecting results instead of sharing mutable state. When sharing is necessary, use AtomicInteger, ConcurrentHashMap or synchronized blocks.

Step by step

  1. Increment a shared int from two threads and observe a wrong total.
  2. Fix it with AtomicInteger.
  3. Run three simulated slow calls with CompletableFuture and combine the results.
  4. Shut down the executor properly.

Practice activity

Fetch three simulated exchange-rate sources in parallel with CompletableFuture and print their average, with a timeout for a slow source.

Expected result: The program finishes in roughly the time of the slowest call, handles the timeout and prints the correct average.

Check your understanding

  1. What is a race condition?

    Show answer

    A bug where the result depends on the timing of threads accessing shared data.

  2. Why use an ExecutorService rather than creating threads directly?

    Show answer

    It manages and reuses a pool of threads and provides a clean way to submit and shut down work.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.