AlgoMaster Logo

Semaphore

Last Updated: June 6, 2026

Medium Priority
21 min read

A Semaphore is a counting set of permits. Threads ask for a permit before doing work, and they hand it back when they're done. If no permit is available, the asker waits. This lesson covers what a semaphore is, how acquire, release, and tryAcquire work, when to use a single-permit semaphore as a non-reentrant mutex, when to use a multi-permit semaphore as a throttle, what the fairness flag does, and the very common bug of leaking permits on failure paths.

The previous chapters covered Lock and ReentrantLock for mutual exclusion, and ReadWriteLock for read-heavy scenarios. A semaphore is a different tool. Locks protect a single critical section. Semaphores count resources. If your goal is "only one thread at a time," a ReentrantLock is appropriate. If your goal is "no more than ten threads at once" or "I have eight database connections and I want to hand them out," that's a semaphore.

Premium Content

Subscribe to unlock full access to this content and more premium articles.