> For the complete documentation index, see [llms.txt](https://amartyushov.gitbook.io/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amartyushov.gitbook.io/tech/programming-languages/java/multithreading/semaphore.md).

# Semaphore

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each [`acquire()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html#acquire--) blocks if necessary until a permit is available, and then takes it. Each [`release()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html#release--) adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the `Semaphore` just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

<figure><img src="https://415484505-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LxtoAXZwwOc4XGto8vb%2Fuploads%2FWkUtHMNNOxEl4fo5WGJt%2FScreenshot%202023-12-05%20at%2010.06.24.png?alt=media&amp;token=88218d3d-c815-4ca9-942a-ea2f5bac5c8f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://415484505-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LxtoAXZwwOc4XGto8vb%2Fuploads%2F6t5A4nVa1Y9Mzk9gI0C0%2FScreenshot%202023-12-05%20at%2010.06.59.png?alt=media&amp;token=7006cfb7-160d-4e8b-a873-c0f4f5602c1e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://415484505-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LxtoAXZwwOc4XGto8vb%2Fuploads%2FYBziaP6NyfEHap9MTAq9%2FScreenshot%202023-12-05%20at%2010.09.02.png?alt=media&amp;token=eb5f85e7-7919-4310-8ee8-d3c429546582" alt=""><figcaption></figcaption></figure>
