Semaphore from Scratch

Medium
ConcurrencySemaphoreMutexResource ManagementThread CoordinationAQS

Problem Statement

Implement a Semaphore from scratch (do not use Java's java.util.concurrent.Semaphore). A semaphore maintains a set of permits. acquire() blocks until a permit is available and then takes one. release() adds a permit, potentially unblocking a waiting thread.

Implement both fair (FIFO ordering) and non-fair variants.

class MySemaphore {
    public MySemaphore(int permits) {}
    public MySemaphore(int permits, boolean fair) {}
    // Acquires 1 permit (blocks if none available)
    public void acquire() throws InterruptedException {}
    // Acquires N permits atomically
    public void acquire(int permits) throws InterruptedException {}
    // Returns true if acquired within timeout, false otherwise
    public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {}
    public void release() {}
    public void release(int permits) {}
    public int availablePermits() {}
    public int getQueueLength() {}
}

Key Entities

  • permits: AtomicInteger counting available permits.
  • ReentrantLock + Condition notEmpty: Waiting threads sleep here; released when permits become available.
  • Wait queue: For fair semaphore, a Queue<Thread> or FIFO Condition queue.

Requirements

  1. Binary semaphore (permits=1) must behave like a mutex.
  2. Counting semaphore with N permits allows N concurrent accesses.
  3. Fair variant: threads are released in FIFO order (no starvation).
  4. Non-fair variant: no ordering guarantee (barging allowed — higher throughput).
  5. acquire(N) must atomically acquire all N permits or block.

Asked at: Google, Amazon, Microsoft, Oracle, Adobe, Uber, Goldman Sachs

!Constraints

- 0 ≤ permits ≤ Integer.MAX_VALUE - release() on a zero-permit binary semaphore must increment to 1 (no cap unless explicitly set). - Fair mode must guarantee FIFO ordering among waiting threads. - acquire(N) where N > totalPermits should never complete (deadlock-avoid scenario). - Thread interruption must propagate InterruptedException from acquire().
Output

Run or submit your code to see output here.