☕ Java Intermediate

What is the Semaphore class in Java?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

A Semaphore maintains a set of permits. acquire() takes a permit (blocking if none available) and release() returns a permit. It controls the number of threads that can access a resource simultaneously. A semaphore with one permit acts as a mutex. A semaphore with N permits allows up to N threads to access a resource concurrently — useful for connection pool management, rate limiting, or controlling access to a fixed number of resources. Unlike synchronized, semaphores are not tied to a specific thread — any thread can call release(), even one that did not call acquire(), enabling flexible signaling patterns.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.