How to Use Counting Semaphore in Concurrent Java Application?
Java Counting Semaphore maintains a specified number of passes or permissions, and the Current Thread must obtain a permit to access a shared resource. If a permit is already exhausted by threads other than that, it may wait until the permit becomes available as a result of the release of permits from various threads. This concurrency utility can be very useful for implementing a pattern of producer-consumer design or implementing limited pools of assets such as Thread Pool, DB Connection Pool, etc. The class java.util.Semaphore is a Counting Semaphore that is initialized with a number of permissions.
Semaphore provides two main methods for obtaining permits and releasing permits
- acquire(): This method acquires a permit if one is available, and returns immediately, reducing the number of available permits by one. If the current thread is interrupted while waiting for a permit then InterruptedException is thrown.
- release(): This method acquires the given number of permits, if they are available, and returns immediately, reducing the number of available permits by the given amount. If the current thread is interrupted while waiting for a permit then InterruptedException is thrown.
Implementation:
A binary semaphore is known as a Counting semaphore with one permit because it only has two state permits available or unavailable permits. To execute mutual exclusion or critical section where only one thread is allowed to execute, a binary semaphore can be used. A thread waits on acquire() until Thread allows release within the critical section by calling release() on the semaphore. Below is java semaphore counting where binary semaphore is used to provide shared exclusive access to essential code parts
Example:
Java
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
Semaphore binary = new Semaphore( 1 );
public static void main(String args[])
{
final SemaphoreTest test = new SemaphoreTest();
new Thread() {
@Override public void run()
{
test.mutualExclusion();
}
}.start();
new Thread() {
@Override public void run()
{
test.mutualExclusion();
}
}.start();
}
private void mutualExclusion()
{
try {
binary.acquire();
System.out.println(
Thread.currentThread().getName()
+ " inside mutual exclusive " );
Thread.sleep( 1000 );
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
binary.release();
System.out.println(
Thread.currentThread().getName()
+ " outside of mutual exclusive " );
}
}
}
|
Output
Thread-0 inside mutual exclusive
Thread-1 inside mutual exclusive
Thread-0 outside of mutual exclusive
Thread-1 outside of mutual exclusive
Last Updated :
08 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...