Site icon

Java concurrency example-Synchronize resources using Semaphore

1. Scenario: Synchronize resources using Semaphore (concurrency/example)

2. Program: Synchronize resources using Semaphore (concurrency/example)

2.1 BookingAgent class:

package org.learn.sema;

public class BookingAgent implements Runnable {

    private Reservation reservation;

    public BookingAgent(Reservation reservation) {
        this.reservation = reservation;
    }

    @Override
    public void run() {
        System.out.println("Initiate booking for "+ Thread.currentThread().getName());
        reservation.book(new Object());
        System.out.println("Successfully booked ticket for "+ Thread.currentThread().getName());
    }
}

2.2 Reservation class:

package org.learn.sema;

import java.util.Random;
import java.util.concurrent.Semaphore;

import static java.lang.Thread.sleep;

public class Reservation {

    private Semaphore semaphore;
    private Random random = new Random();

    public Reservation() {
        semaphore = new Semaphore(1);
    }

    public void book(Object personalInfo) {

        try {
            semaphore.acquire();
            int duration = random.nextInt(100);
            System.out.printf("Time taken to book ticket for %s : %d\n",
                    Thread.currentThread().getName(), duration);
            sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}

2.3 SemaphoreExample class:

package org.learn.sema;

public class SemaphoreExample {
    public static void main(String[] args) throws InterruptedException {

        Reservation reservation = new Reservation();
        BookingAgent bookingAgent = new BookingAgent(reservation);

        for (int i = 1; i <= 5; i++) {
            Thread passenger = new Thread(bookingAgent, "Passenger "+i);
            passenger.start();
        }
    }
}

3. Output: Conurrency access to resources using Semaphore (java /example)

Initiate booking for Passenger 1
Initiate booking for Passenger 3
Initiate booking for Passenger 5
Initiate booking for Passenger 4
Initiate booking for Passenger 2
Time taken to book ticket for Passenger 1 : 47
Successfully booked ticket for Passenger 1
Time taken to book ticket for Passenger 3 : 60
Successfully booked ticket for Passenger 3
Time taken to book ticket for Passenger 5 : 78
Successfully booked ticket for Passenger 5
Time taken to book ticket for Passenger 4 : 64
Successfully booked ticket for Passenger 4
Time taken to book ticket for Passenger 2 : 67
Successfully booked ticket for Passenger 2
Exit mobile version