Skip to content

Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 4 of 5

Synchronisation and Thread Safety

Race conditions, synchronized methods and blocks, the volatile keyword, atomic variables, concurrent collections, deadlock and how to avoid it.

Beginner 18 min read·Lesson 38 of 39 in Java Programming

Learning objectives

  • Recognise and reproduce a race condition
  • Fix races with synchronized, atomic variables and concurrent collections
  • Explain visibility, volatile and how deadlocks happen

Definition

Thread safety means that code behaves correctly when executed by several threads at once. Synchronisation coordinates access to shared mutable data so that compound operations are atomic and changes made by one thread are visible to others.

Introduction

Threads become dangerous the moment they share data that changes. count++ looks like one step, but it is really three — read, add, write — and two threads can interleave those steps so that an increment is lost. This lesson shows the bug and the standard ways to prevent it.

Why it matters

Concurrency bugs are rare, timing-dependent and hard to reproduce, so they must be prevented by design.

Banking, inventory and booking systems all have to stay correct under concurrent updates.

Detailed explanation

Race conditions. When the result depends on the timing of threads, there is a race. count++ on a shared field, check-then-act (if (!map.containsKey(k)) map.put(k, v)) and read-modify-write sequences are classic examples.

synchronized. Every object has an intrinsic lock. A synchronized method (or synchronized (lock) { ... } block) lets only one thread at a time hold the lock, so the code inside runs atomically with respect to other code synchronised on the same lock. Exiting the block — even through an exception — releases the lock.

Visibility. Without synchronisation, one thread may not see another thread's writes (values can be cached). Releasing and acquiring the same lock guarantees visibility. volatile on a field also guarantees visibility, but not atomicity — it suits simple flags like running = false.

Atomic variables. AtomicInteger, AtomicLong and LongAdder provide lock-free atomic operations such as incrementAndGet and addAndGet.

Concurrent collections. ConcurrentHashMap (with atomic merge and computeIfAbsent), CopyOnWriteArrayList and BlockingQueue implementations (for producer–consumer designs) are safe to share.

Deadlock. If thread A holds lock 1 and waits for lock 2 while thread B holds lock 2 and waits for lock 1, both wait forever. Avoid it by always acquiring locks in the same global order, holding locks briefly, or using tryLock with a timeout from java.util.concurrent.locks.

The best strategy is often to avoid sharing: give each thread its own data and combine results at the end, or share only immutable objects.

Syntax

Java
class Counter {
private int count;
synchronized void increment() { count++; } // one thread at a time
synchronized int get() { return count; }
}
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet(); // atomic, lock-free
Map<String, Integer> freq = new ConcurrentHashMap<>();
freq.merge(word, 1, Integer::sum); // atomic per key
private volatile boolean running = true; // visibility only
  • Synchronise both reads and writes of shared mutable state.
  • volatile does not make count++ atomic.
  • Lock objects should be private and final.

Code examples

A race condition and its fix

Java
public class Main {
static int unsafeCount = 0;
static int safeCount = 0;
static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
unsafeCount++; // read, add, write: not atomic
synchronized (lock) { safeCount++; } // one thread at a time
}
};
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println("synchronized count: " + safeCount);
System.out.println("unsynchronized count is at most 200000: " + (unsafeCount <= 200_000));
}
}
Output
synchronized count: 200000
unsynchronized count is at most 200000: true

Run it a few times and print unsafeCount itself: it is usually less than 200,000, and different each time, because increments are lost.

Atomic variables and a volatile flag

Java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
AtomicInteger counter = new AtomicInteger();
Thread[] ts = new Thread[4];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(() -> { for (int j = 0; j < 25_000; j++) counter.incrementAndGet(); });
ts[i].start();
}
for (Thread t : ts) t.join();
System.out.println("atomic counter: " + counter.get());
Thread worker = new Thread(() -> { while (running) Thread.onSpinWait(); });
worker.start();
Thread.sleep(20);
running = false; // the worker sees this change because the field is volatile
worker.join();
System.out.println("worker stopped: " + !worker.isAlive());
}
}
Output
atomic counter: 100000
worker stopped: true

More examples

A thread-safe bank and a lock-ordering rule

Java
import java.util.*;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
Bank bank = new Bank();
Account a = bank.open("A", 10_000), b = bank.open("B", 10_000), c = bank.open("C", 10_000);
List<Account> all = List.of(a, b, c);
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 3_000; i++) {
Account from = all.get(i % 3), to = all.get((i + 1) % 3);
pool.submit(() -> bank.transfer(from, to, 7));
pool.submit(() -> bank.transfer(to, from, 5)); // opposite direction: deadlock-prone without ordering
}
}
System.out.println("A=" + a.balance() + " B=" + b.balance() + " C=" + c.balance());
System.out.println("total preserved: " + (a.balance() + b.balance() + c.balance() == 30_000));
Map<String, Integer> visits = new ConcurrentHashMap<>();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int i = 0; i < 10_000; i++) {
String page = i % 4 == 0 ? "/home" : "/blog";
pool.submit(() -> visits.merge(page, 1, Integer::sum)); // atomic per key
}
}
System.out.println(new TreeMap<>(visits));
}
}
class Account {
final int id;
private long balance;
Account(int id, long balance) { this.id = id; this.balance = balance; }
synchronized long balance() { return balance; }
void add(long amount) { balance += amount; } // only called while holding this account's lock
}
class Bank {
private int nextId = 1;
synchronized Account open(String name, long opening) { return new Account(nextId++, opening); }
void transfer(Account from, Account to, long amount) {
Account first = from.id < to.id ? from : to; // always lock the lower id first
Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
if (from.balance() < amount) return;
from.add(-amount);
to.add(amount);
}
}
}
}
Output
A=10000 B=10000 C=10000
total preserved: true
{/blog=7500, /home=2500}

Step-by-step explanation

  • Thousands of transfers run concurrently on eight threads, including transfers in opposite directions between the same two accounts.
  • transfer always locks the account with the lower id first. Because every thread uses the same order, two transfers can never each hold one lock while waiting for the other — no deadlock.
  • Holding both locks makes the check and the two updates atomic, so money is never lost or created: the total stays 30,000. (Each pair of accounts receives exactly as many +7/−5 transfers in each direction, so the balances also end where they started.)
  • Calling balance() again inside the blocks is fine because Java locks are re-entrant: a thread may re-acquire a lock it already holds.
  • ConcurrentHashMap.merge updates each key atomically, so all 10,000 visits are counted without any explicit locking.

Expected output

Running “A thread-safe bank and a lock-ordering rule” prints exactly:

TextOutput
A=10000 B=10000 C=10000
total preserved: true
{/blog=7500, /home=2500}

Practical applications

  • Bank transfers, stock updates and seat booking under concurrent requests
  • Shared caches and counters in web servers
  • Producer–consumer pipelines with BlockingQueue
  • Stop flags for background workers

Best practices

  • Prefer immutable data and thread confinement to shared mutable state.
  • Use atomic classes and concurrent collections before writing your own locking.
  • Keep synchronized blocks short and never call unknown code while holding a lock.

Common mistakes

Thinking volatile makes increments safe

Avoid

private volatile int count;
void hit() { count++; }

Prefer

private final AtomicInteger count = new AtomicInteger();
void hit() { count.incrementAndGet(); }

volatile guarantees visibility, but count++ is still a separate read and write that can interleave.

Locking in inconsistent order

Avoid

synchronized (from) { synchronized (to) { ... } }

Prefer

Account first = from.id < to.id ? from : to;
Account second = first == from ? to : from;
synchronized (first) { synchronized (second) { ... } }

Two transfers in opposite directions can each grab one lock and wait for the other forever; a global lock order prevents it.

Important notes

  • The unsynchronised count in the first example varies from run to run, so the example prints only a fact that is always true about it.
  • java.util.concurrent.locks.ReentrantLock offers tryLock, timeouts and fairness when synchronized is not flexible enough.

Key takeaways

  • Shared mutable state accessed by several threads needs synchronisation.
  • synchronized gives atomicity and visibility; volatile gives visibility only.
  • Use AtomicInteger, ConcurrentHashMap and consistent lock ordering; avoid deadlocks.

Try it yourself

  1. 1
    Write a thread-safe Inventory class whose reserve(item, qty) never lets stock go negative.
  2. 2
    Implement a producer–consumer pair with an ArrayBlockingQueue of capacity 5.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhy is `volatile int count; count++;` still unsafe with several threads?
  • AdvancedWhat is printed?
  • AdvancedTwo threads run `synchronized (a) { synchronized (b) { ... } }` and `synchronized (b) { synchronized (a) { ... } }`. What can happen?
Practise this topic