QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Parallelism

synchronized, volatile, atomic and ExecutorService

count++ is three steps: read, add one, write back, so two threads can read the same value and one increment is lost. Both atomicity and visibility are needed: use AtomicInteger for a counter, synchronized for a group of fields and ConcurrentHashMap for a shared map. volatile gives visibility only, not atomicity. For a race test, start threads through an ExecutorService with a shared start on a CountDownLatch.

Java · Concurrency

Two hundred tests bump one counter and the result differs every run. What is wrong with count++?

The line count++ looks like one action, yet it breaks parallel tests in a way that is hard to reproduce. Besides shared counters and maps, tests sometimes need the opposite task: start several threads on purpose to check a race between two orders. This lesson covers both sides.

How it works and why. count++ is three steps: read the value, add one, write it back. The scheduler may switch threads between steps, so two threads read the same number and one increment disappears. The second problem is visibility: without synchronisation a thread may not see another thread's write because the value may stay in a register, and the compiler and CPU may reorder operations. The tools solve two different tasks: atomicity (the operation is indivisible) and visibility (changes are seen by other threads).

A lost increment

Thread 1 reads 5thread 2 also reads 5Both: 5 + 1 = 6each in its own registersBoth write 6expected 7, one is lost
Figure 1. Both threads read 5 before anyone wrote, so the result is 6 instead of 7.
ToolWhat it guaranteesWhen to use
AtomicIntegerAtomic incrementAndGet(), addAndGet(), CAS (compareAndSet) without a lockCounters
synchronizedOne thread in the section and visibility of changesSeveral fields changed together
volatileVisibility only, not atomicityA "stop" flag
ConcurrentHashMapSafe map operationsA shared token cache
ExecutorServiceA thread pool and FutureYour own parallel requests in a test

Example: before → after. Typical shared state in a test project:

// a shared counter and map in parallel tests
static int created = 0;
static Map<String, String> tokens = new HashMap<>();

created++;                          // three steps: read, +1, write
tokens.put(user, login(user));      // HashMap is not for parallel writes

The fix uses an atomic counter and a thread-safe map. computeIfAbsent logs in once per user instead of "check that it is missing, then put" in two steps (while the login runs, some writes by other threads to the map wait, so the function should be short):

static final AtomicInteger created = new AtomicInteger();
static final Map<String, String> tokens = new ConcurrentHashMap<>();

created.incrementAndGet();                        // atomic
String token = tokens.computeIfAbsent(user, u -> login(u));  // one login per user

Your own threads in a test. Sometimes the race is the subject of the check: five clients buy the last item and exactly one should win. For this use an ExecutorService, and a CountDownLatch gives a common start, otherwise the first thread finishes before the fifth one starts:

try (ExecutorService pool = Executors.newFixedThreadPool(5)) {
    CountDownLatch start = new CountDownLatch(1);
    List<Future<Integer>> results = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        results.add(pool.submit(() -> {
            start.await();                   // everyone starts together
            return client.buyLastItem(cart).status();
        }));
    }
    start.countDown();
    List<Integer> codes = new ArrayList<>();
    for (Future<Integer> f : results) codes.add(f.get(10, TimeUnit.SECONDS));
    assertThat(codes).containsOnlyOnce(201);   // only one order succeeds
}   // close() waits for the tasks
  • submit returns a Future; get(timeout) waits for the result and throws ExecutionException with the cause if the task failed. An exception in a pool thread otherwise goes nowhere.
  • The pool must be stopped: shutdown() and awaitTermination, otherwise its threads keep the JVM alive. Since Java 19 ExecutorService has close(), so try-with-resources works, as above.
  • Always pass a timeout to get: without it a stuck task hangs the whole test. But close() also waits for every task to finish, so after a TimeoutException the stuck task holds the test at the pool close. If a task can hang, call pool.shutdownNow() in a catch or finally (the task must react to interruption, and the HTTP client needs its own timeout).
  • Java 21 has virtual threads: Executors.newVirtualThreadPerTaskExecutor() is convenient for many calls that block a thread on the network.

Limits and alternatives.

  • synchronized is safe but costlier. If several locks are taken in different orders, a deadlock appears: two threads wait for each other forever. Rule: keep the section short and do not call foreign code inside it.
  • volatile does not make ++ atomic. It fits a flag that one thread writes and others read.
  • A thread-safe collection protects single operations, not a composite scenario. if (!map.containsKey(k)) map.put(k, v) is still a race; here one call to computeIfAbsent or putIfAbsent is needed.
  • The best shared state is no shared state. Counters in tests are often easier to replace with data per test.
  • A race test is a probabilistic check: a green run does not prove the bug is absent. A server-side race is closed with transactions or unique constraints, and the test only confirms it.

Typical mistakes.

  • Using volatile int as a counter.
  • Reading Future.get() without a timeout and not stopping the pool.
  • Collecting results from many threads into a plain ArrayList.
  • Adding synchronized everywhere "just in case": it hides the problem and slows the run.
  • Starting threads without a common start and assuming the race was exercised.

Check yourself

Why does volatile int counter with counter++ not give a correct sum?

Answer

volatile guarantees visibility of the write, but ++ is still three steps (read, add, write). Two threads can read the same value, so an increment is lost. AtomicInteger or synchronized is needed.

What does CountDownLatch do in a test for a race between two orders?

Answer

All threads wait on the latch and start at the same moment after countDown(). Without it the first thread may finish before the last one starts, and there is no contention.

Why is if (!map.containsKey(k)) map.put(k, v) still unsafe even for a ConcurrentHashMap?

Answer

The collection protects each call separately, and between the check and the put another thread can insert a value. A composite action is done with one atomic call: computeIfAbsent or putIfAbsent.

In the interview. Junior: count++ is read, add and write, so two threads lose an increment. For a counter I take AtomicInteger, for a group of fields synchronized, for a shared map ConcurrentHashMap. volatile gives only visibility. Middle/Senior: I separate atomicity from visibility and try to remove shared state rather than protect it. For a race test I use an ExecutorService with a common start through CountDownLatch, a timeout in Future.get and a closed pool. I know such a test is only probabilistic: the race itself is closed by the server (a transaction, a unique key), and the test checks that it is closed.

More articles in this chapter