Semaphore – Java Concurrency

Semaphore is used to control the number of threads that can access a resource. The Semaphore class in the java.util.concurrent package represents the semaphore synchronizer.
You create a semaphore using one of its constructors, like so:

Semaphore semaphore = new Semaphore (MAX PERMITS)

Two important methods in Semaphore are:

acquire: blocks if necessary until a permit is available, and then takes it.release: adds a permit, potentially releasing a blocking acquirer

A semaphore has basically two uses:

To guard a critical section against entry by more than the permitted number of threads at a time.

To send signals between threads.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the “lock” can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource.