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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With