Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Redisson Semaphore auto release

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.

like image 531
Swagat Avatar asked Aug 23 '18 09:08

Swagat


1 Answers

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.

like image 53
Sagar Salokhe Avatar answered Nov 09 '22 00:11

Sagar Salokhe