6

I am using RSemaphore to maintain a particular count. Please take a look below:-

RSemaphore sem = redisson.getSemaphore("custid=10");
sem.trySetPermits(10);
  try {
     sem.acquire();
  } catch (InterruptedException e) {
     e.printStackTrace();
  }

  System.out.println(Thread.currentThread().getName() + ": Acquired permit");

  try {
     Thread.sleep(60000);
  } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }

  System.out.println(Thread.currentThread().getName() + ": Releasing permit");
  sem.release();

I am releasing the Semaphore at the end, but sometimes it's possible that my code execution will stop, get terminated or I stop the server because of a particular reason. Then the acquire Semaphore will never get released.

To handle this scenario I want the Semaphore which will release itself automatically after a particular time.

Swagat
  • 709
  • 3
  • 9
  • 27

2 Answers2

3

You should use PermitExpirableSemaphore as below:

RPermitExpirableSemaphore semaphore =redisson.getPermitExpirableSemaphore("mySemaphore"); 

// acquire permit with lease time = 2 seconds 
String permitId = semaphore.acquire(2, TimeUnit.SECONDS);
// ... Do something 
semaphore.release(permitId);

The semaphore will be released automatically after 2 seconds by default.

Sagar Salokhe
  • 276
  • 3
  • 7
0

I would recommend to use one try block with finally, where the semaphore is released.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 15 '23 at 21:55
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34684554) – user12256545 Jul 17 '23 at 18:26