AlgoViz

Semaphore

medium 45 min

A semaphore is a counter of permits with a waiting line.

Watch lesson4:38

Where it shows up

The same pattern appears across everyday software.

  • Java Semaphore

    java.util.concurrent.Semaphore, since Java 5. Unfair by default, and its documentation says that barging is then permitted. Any thread may release, there is no ownership.

  • Python threading and asyncio

    threading has Semaphore and BoundedSemaphore, which raises ValueError when released too often. asyncio has both as well, for tasks on one event loop and explicitly not for threads.

  • Go x/sync/semaphore

    A weighted semaphore: each acquire names how much it takes. Its source keeps the rest of the line waiting behind a large request, so that large ones do not starve.

  • Linux kernel

    The kernel documentation names semaphores as the exception among its lock types: they have no strict owner, every other type must be released by the task that acquired it.

  • Resilience4j

    Its SemaphoreBulkhead limits concurrent calls to a dependency. The documented defaults are 25 concurrent calls and a maximum wait of 0.

  • nginx limit_conn

    Limits the number of connections per key, for example per client address. A limit on concurrency, next to limit_req for rates.

  • pgx and puddle

    Puddle, the resource pool below the Go PostgreSQL driver pgx, holds a weighted semaphore for acquiring and a mutex for its lists: how many, and which one.

  • HikariCP

    The connection pool hands connections over with its own concurrent bag, a counter of waiters and a SynchronousQueue. A Semaphore with 10,000 permits sits in its suspend and resume lock: suspending takes them all.

  • Apache Curator

    The shared semaphore recipe on ZooKeeper gives out leases across processes, and describes itself as mostly fair, in the order requested.

  • Redisson

    Offers a distributed semaphore on Redis or Valkey, and a PermitExpirableSemaphore whose permits have their own id and a lease time, and can only be released with that id.