multi threading
advanced

Locks & Synchronizers

Use explicit locks (ReentrantLock, ReadWriteLock) and synchronizers (Semaphore, CountDownLatch, CyclicBarrier) when synchronized isn't enough.

The synchronized keyword is simple but inflexible: you cannot try to acquire a lock and give up, you cannot interrupt a thread waiting for it, you cannot time out, and you cannot acquire in one method and release in another. The java.util.concurrent.locks package and the synchronizer classes provide explicit, more capable building blocks for exactly the cases where intrinsic locks fall short.

ReentrantLock = a room key with a timer (give up if waiting too long). ReadWriteLock = a library reading room (many readers, one writer). Semaphore = a parking lot with K spots. CountDownLatch = a starting gun (wait until ready). CyclicBarrier = relay runners meeting at each lap.

Key Concepts

1
ReentrantLock is the direct, more powerful replacement for synchronized: you call lock() and unlock() yourself (always in a try/finally so the lock is released on exceptions), and in return you gain tryLock() with an optional timeout, interruptible acquisition, and an optional fairness policy. ReadWriteLock splits access into a shared read lock and an exclusive write lock, so many readers can proceed concurrently while writers get exclusivity — a big win for read-heavy data. The synchronizers solve coordination rather than mutual exclusion: a Semaphore limits how many threads may access a resource at once (a connection pool of N permits); a CountDownLatch makes threads wait until a one-time count reaches zero (wait for N services to start); and a CyclicBarrier makes a group of threads wait for each other at a rendezvous point, then releases them together, and resets for reuse.
ReentrantLocksynchronizedlock()unlock()try/finally
2
The defining trade-off is power versus discipline. synchronized releases its lock automatically when the block exits, even on an exception; an explicit Lock does not, so a missing unlock() in a finally is a classic source of permanently stuck threads. The interview-favourite contrast is CountDownLatch versus CyclicBarrier: the latch counts down once and cannot be reused, while the barrier is cyclic and reusable, and the barrier's threads wait for each other rather than for an external event.
synchronizedLockunlock()finallyCountDownLatch