In Java, a Semaphore is a synchronization primitive that allows controlling access to a limited number of resources. It is essentially a counter that is initialized with a specific value and decremented when a resource is acquired, and incremented when it is released. If the counter is zero, then any thread trying to acquire a resource is blocked until another thread releases one.
The Semaphore class in Java provides two main methods: acquire() and release(). The acquire() method is used to acquire a permit, which decrements the counter, and the release() method is used to release a permit, which increments the counter. These methods can be used in a synchronized block or method to ensure that only one thread at a time can modify the semaphore.
Hereβs an example of how to use Semaphore in Java:
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
// create a semaphore with 2 permits
Runnable task = () -> {
try {
semaphore.acquire(); // acquire a permit
System.out.println(Thread.currentThread().getName()
+ " acquired a permit");
Thread.sleep(1000); // simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // release a permit
System.out.println(Thread.currentThread().getName()
+ " released a permit");
}
};
new Thread(task, "Thread 1").start();
new Thread(task, "Thread 2").start();
new Thread(task, "Thread 3").start();
new Thread(task, "Thread 4").start();
}
}
In this example, we create a Semaphore with two permits and define a task that acquires a permit, does some work for one second, and then releases the permit. We then create four threads that execute this task. Since the semaphore has only two permits, only two threads can acquire a permit at a time. The output of the program might look something like this:
Thread 1 acquired a permit
Thread 2 acquired a permit
Thread 2 released a permit
Thread 1 released a permit
Thread 3 acquired a permit
Thread 4 acquired a permit
Thread 4 released a permit
Thread 3 released a permit
As you can see, only two threads acquire a permit at a time, and the other threads are blocked until a permit is released. This can be useful in scenarios where you want to limit the number of concurrent accesses to a resource, such as a database connection pool or a shared resource with a limited capacity.