How to Use Counting Semaphore in Concurrent Java Application? Last Updated : 24 Apr, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report 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 { // Create a semaphore with a single permit Semaphore binary = new Semaphore(1); public static void main(String args[]) { final SemaphoreTest test = new SemaphoreTest(); // Create and start the first thread new Thread() { @Override public void run() { test.mutualExclusion(); } }.start(); // Create and start the second thread new Thread() { @Override public void run() { test.mutualExclusion(); } }.start(); } private void mutualExclusion() { try { // Try to acquire the semaphore binary.acquire(); // Synchronized block to ensure sequential printing for each thread synchronized (System.out) { // Print a message indicating that the current thread is inside the mutual exclusive region System.out.println(Thread.currentThread().getName() + " inside mutual exclusive "); } // Make the current thread sleep for 1 second Thread.sleep(1000); } catch (InterruptedException e) { // Print the stack trace for the InterruptedException e.printStackTrace(); } finally { // Release the semaphore binary.release(); // Synchronized block to ensure sequential printing for each thread synchronized (System.out) { // Print a message indicating that the current thread is outside the mutual exclusive region System.out.println(Thread.currentThread().getName() + " outside of mutual exclusive "); } } } } OutputThread-0 inside mutual exclusive Thread-1 inside mutual exclusive Thread-0 outside of mutual exclusive Thread-1 outside of mutual exclusive Comment More infoAdvertise with us Next Article ConcurrentLinkedDeque size() method in Java K kapilnama1998 Follow Improve Article Tags : Java Java-Multithreading Practice Tags : Java Similar Reads Java.util.concurrent.Semaphore Class in Java A semaphore controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. What the counter is counting are permits that allow access to the shared resource. Thus, to access the resource, a thread 6 min read Need of Concurrent Collections in java In Java, multiple threads can work at the same time, but when the applications become complex, it is very important to handle multiple threads at the same time. With the help of concurrency, different tasks can run in parallel, which can improve the performance of the application. Managing shared da 3 min read How Does ConcurrentHashMap Achieve Thread-Safety in Java? ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class Co 6 min read ConcurrentHashMap size() Method in Java The size() method in Java's ConcurrentHashMap class is used to retrieve the number of key-value mappings in the map. It has the following signature: int size() The size() method works in a concurrent environment, which means that it can be called from multiple threads without causing any data race o 2 min read ConcurrentLinkedDeque size() method in Java The size() method of ConcurrentLinkedDeque class in Java is used to find the number of elements present in the ConcurrentLinkedDeque container. In other words, this method tells the current capacity of the container. The value returned by this method is of integral type and in case if the container 2 min read ConcurrentLinkedQueue size() method in Java The size() method of ConcurrentLinkedQueue is used to returns number of elements that this ConcurrentLinkedQueue contains. Syntax: public int size() Returns: This method number of elements in this ConcurrentLinkedQueue. Below programs illustrate size() method of ConcurrentLinkedQueue: Example 1: Jav 2 min read Like