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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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.
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
Thread-0 inside mutual exclusive Thread-1 inside mutual exclusive Thread-0 outside of mutual exclusive Thread-1 outside of mutual exclusive