Lesson 2 of 8
Synchronisation - Race Conditions & Locks
When multiple threads access shared mutable state, race conditions produce incorrect, non-deterministic results. Synchronisation coordinates thread access to ensure atomicity and visibility. The synchronized keyword is Java's built-in lock mechanism.
Race Condition & synchronized
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
public class SynchronisationDemo {
// ❌ RACE CONDITION - not thread-safe
static int unsafeCounter = 0;
static void unsafeIncrement() { unsafeCounter++; } // 3 operations: read, add, write
// ✅ synchronized method - one thread at a time on THIS object's monitor
static class SafeCounter {
private int count = 0;
public synchronized void increment() { count++; }
public synchronized int getCount() { return count; }
// synchronized block - finer granularity (lock only what's needed)
public void incrementBlock() {
// "expensive work that doesn't need locking"
synchronized (this) {
count++;
}
// "more expensive work outside lock"
}
}
// ✅ Atomic variables - lock-free, faster than synchronized for single variables
static AtomicInteger atomicCounter = new AtomicInteger(0);
static void atomicIncrement() { atomicCounter.incrementAndGet(); }
// AtomicReference - compare-and-swap for objects
static AtomicLong totalValue = new AtomicLong(0);
static void addToTotal(long amount) {
totalValue.addAndGet(amount); // atomic add
}
// ✅ ReentrantLock - explicit, more flexible than synchronized
static final Lock lock = new ReentrantLock();
static int lockedCounter = 0;
static void lockedIncrement() {
lock.lock(); // acquire lock
try {
lockedCounter++;
} finally {
lock.unlock(); // MUST be in finally - unlock even on exception
}
}
// ReentrantReadWriteLock - many readers OR one writer (not both)
static final ReadWriteLock rwLock = new ReentrantReadWriteLock();
static Map<String, Book> catalog = new HashMap<>();
static Book getBook(String isbn) {
rwLock.readLock().lock(); // multiple threads can hold read lock simultaneously
try {
return catalog.get(isbn);
} finally {
rwLock.readLock().unlock();
}
}
static void addBook(Book book) {
rwLock.writeLock().lock(); // exclusive - no readers or other writers
try {
catalog.put(book.getIsbn(), book);
} finally {
rwLock.writeLock().unlock();
}
}
}Quick Quiz
Tip
Tip
Practice Synchronisation Race Conditions Locks in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Synchronisation - Race Conditions & Locks
Practice Task
Note
Practice Task - (1) Write a working example of Synchronisation Race Conditions Locks from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Synchronisation Race Conditions Locks is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?