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.
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
- 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
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
atomic counter: 100000 worker stopped: true
More examples
A thread-safe bank and a lock-ordering rule
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.
transferalways 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.mergeupdates 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:
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
Prefer
volatile guarantees visibility, but count++ is still a separate read and write that can interleave.
Locking in inconsistent order
Avoid
Prefer
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
- 1Write a thread-safe
Inventoryclass whosereserve(item, qty)never lets stock go negative. - 2Implement 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?