top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java : Semaphore Concept and Example


Introduction: A semaphore is a synchronization tool that restricts access to shared resources or critical sections of code by using a counter that determines how many threads can access the resource or section at the same time. In Java, the Semaphore class is used to implement semaphores.

Explanation: A Semaphore has two methods of interest: acquire() and release(). acquire() decrements the counter of the Semaphore and blocks the thread if the counter reaches zero, while release() increments the counter and wakes up any blocked threads if the counter is greater than zero.

Here is an example code that demonstrates the use of a Semaphore to limit the number of threads that can access a shared resource at the same time:


import java.util.concurrent.Semaphore;

public class SemaphoreExample {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2); // initialize a Semaphore with a counter of 2Runnable task = () -> {
            try {
                semaphore.acquire(); // acquire a permit from the Semaphore
                System.out.println(Thread.currentThread().getName() + " acquired permit.");
                Thread.sleep(1000); // simulate doing some work
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release(); // release the permit back to the Semaphore
                System.out.println(Thread.currentThread().getName() + " released permit.");
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        Thread thread3 = new Thread(task);

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

In this example, we create a Semaphore with a counter of 2. We then create a Runnable task that acquires a permit from the Semaphore, sleeps for 1 second to simulate some work, and then releases the permit back to the Semaphore. We create three threads that execute the task.

Since the Semaphore has a counter of 2, only two threads can acquire a permit at the same time. The third thread will be blocked until one of the other two threads releases its permit back to the Semaphore.

Sample Output:


Thread-0 acquired permit.
Thread-1 acquired permit.
Thread-1 released permit.
Thread-0 released permit.
Thread-2 acquired permit.
Thread-2 released permit.

As expected, only two threads acquire a permit at the same time, while the third thread is blocked until one of the other two threads releases its permit back to the Semaphore.

271 views

Recent Posts

See All

Comments


bottom of page