Java semaphore
Java Semaphore
is a synchronization primitive that is used to control access to a shared resource. It maintains a set of permits that can be acquired and released by threads. The number of permits available determines how many threads can access the shared resource simultaneously.
A Semaphore
can be created by passing an initial number of permits to the constructor. When a thread wants to access the shared resource, it calls the acquire()
method on the Semaphore
. If there are available permits, the acquire()
method decrements the number of permits and allows the thread to access the shared resource. If there are no permits available, the thread will block until a permit becomes available.
When a thread is done accessing the shared resource, it calls the release()
method on the Semaphore
, which increments the number of available permits. If there are threads waiting to acquire permits, the release()
method unblocks one of them and allows it to access the shared resource.
Here's an example of how to use Semaphore
in Java to control access to a shared resource:
Semaphore semaphore = new Semaphore(3); // 3 permits // Thread 1 semaphore.acquire(); try { // access the shared resource } finally { semaphore.release(); } // Thread 2 semaphore.acquire(); try { // access the shared resource } finally { semaphore.release(); }
In this example, a Semaphore
with 3 permits is created. Two threads try to access the shared resource by calling acquire()
on the Semaphore
. Since there are 3 permits available, both threads are allowed to access the shared resource. When they are done, they call release()
to release the permits and allow other threads to access the shared resource.
It's important to note that if a thread calls acquire()
when there are no available permits, it will block until a permit becomes available. Similarly, if a thread calls release()
when no threads are waiting to acquire permits, the extra permit will be saved for future use.
Semaphore
can be a useful tool for managing access to shared resources in multi-threaded applications, especially in scenarios where there is a limit to the number of threads that can access the resource simultaneously.