Advertisement
Kostiggig

Bounded semaphore

May 3rd, 2023
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. package multithreading.semaphore.bounded;
  2.  
  3. public class MyBoundedSemaphore {
  4.  
  5.     private final int maxAcquiresAtTime;
  6.     private int currAcquiresCount = 0;
  7.  
  8.     public MyBoundedSemaphore(int maxAcquiresAtTime) {
  9.         this.maxAcquiresAtTime = maxAcquiresAtTime;
  10.     }
  11.  
  12.     public synchronized void acquire() throws InterruptedException {
  13.         while(currAcquiresCount >= maxAcquiresAtTime) wait();
  14.         currAcquiresCount++;
  15.     }
  16.  
  17.     public synchronized void release() {
  18.         notifyAll();
  19.         currAcquiresCount--;
  20.     }
  21. }
  22.  
  23.  
  24. package multithreading.semaphore.bounded;
  25.  
  26. import java.util.Random;
  27.  
  28. public class Api {
  29.  
  30.     private final MyBoundedSemaphore semaphore;
  31.  
  32.     public Api(MyBoundedSemaphore semaphore) {
  33.         this.semaphore = semaphore;
  34.     }
  35.  
  36.     private final Random random = new Random();
  37.  
  38.     public void makeRequest() throws InterruptedException {
  39.         semaphore.acquire();
  40.         System.out.println("Thread " + Thread.currentThread().getName() + " making a request");
  41.         // Making a request...
  42.         Thread.sleep(3000 + random.nextInt(10) * 500);
  43.         System.out.println("Thread " + Thread.currentThread().getName() + " takes response from the server");
  44.         semaphore.release();
  45.     }
  46. }
  47.  
  48.  
  49. Client:
  50. package multithreading.semaphore.bounded;
  51.  
  52. public class Client {
  53.  
  54.     public static void main(String[] args) throws InterruptedException {
  55.         MyBoundedSemaphore semaphore = new MyBoundedSemaphore(2);
  56.         Api api = new Api(semaphore);
  57.  
  58.         for (int i = 0; i < 4; i++) {
  59.             new Thread(() -> {
  60.                 try {
  61.                     api.makeRequest();
  62.                 } catch (InterruptedException e) {
  63.                     throw new RuntimeException(e);
  64.                 }
  65.             }, "Thread " + i).start();
  66.         }
  67.  
  68.         Thread.sleep(30000);
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement