intermediateConcurrency Utilities

What is a Semaphore, and how is it different from a mutex?

A Semaphore maintains a fixed number of permits: calling acquire() takes one permit, blocking if none are currently available, and calling release() returns one permit back to the pool. A semaphore configured with exactly one permit behaves superficially like a mutex, but there are important differences. A mutex enforces ownership -- only the thread that acquired it is allowed to release it -- whereas a Semaphore has no notion of ownership at all and any thread can call release(), even one that never called acquire(). A Semaphore is fundamentally just a counter, not a lock with acquire-release semantics tied to a specific thread. It also doesn't support reentrancy: a thread that calls acquire() twice against a semaphore with no permits remaining will simply block forever, unlike a reentrant lock. Semaphores are commonly used for rate limiting a maximum number of concurrent operations, managing connection pools, or generally controlling access to a bounded resource.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is ExecutorCompletionService, and when is it useful?← Back to all Java Concurrency & Multithreading questions