Java › Concurrency & Threads
What is the synchronized keyword, and how does it use Java's intrinsic (monitor) locks to prevent race conditions on shared mutable state?
IntermediateAnswer
synchronized (applied to a method, or as a block with an explicit object reference) ensures only one thread at a time can execute the protected code while holding that object's intrinsic monitor lock, with other threads attempting to enter blocking until the lock is released -- this prevents race conditions where multiple threads read-modify-write shared state concurrently in an interleaved, inconsistent way, though it comes with the cost of serializing access (potentially becoming a contention bottleneck) and the risk of deadlock if locks are acquired in inconsistent orders across different code paths.
public class Counter {
private int count = 0;
public synchronized void increment() { // locks 'this' for the duration of the method
count++; // without synchronization, this read-modify-write is NOT atomic and races under concurrency
}
public synchronized int getCount() {
return count;
}
}Real-world example A shared counter incremented by multiple concurrent request-handling threads without synchronization exhibits a classic race condition ("lost updates", where the final count is lower than the actual number of increments due to interleaved read-modify-write operations), fixed by synchronizing the increment method to ensure each increment completes atomically.