Swagat
Swagat

Reputation: 789

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.

Upvotes: 6

Views: 1268

Answers (2)

Dusot Dusot
Dusot Dusot

Reputation: 1

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

Upvotes: 0

Sagar Salokhe
Sagar Salokhe

Reputation: 276

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.

Upvotes: 3

Related Questions