开发者

Delay notification for lock acquisition in Java

We have a use case where we need to acquire a lock and send a notification if acquiring the lock takes more than 5 mins. We should still be waiting for the lock forever.

We are using re-entrant locks and lock.tryLock(5, TimeUnit.Minutes) is not enough as it comes out after 5 minutes.

The option that we tried was:

while(!lock.tryLock(5, TimeUnit.minutes)) {
    // send notification
}

But I guess, this would result in losing the fairness of the lock (order in which lock has been requested for)

Did anyone face such use cases, if yes, please explain how it was solved.

We prefer not to have hand-rolled solution of maintaining the locks and corresponding wait thread's meta info (like when it was initiated for lock acquisition开发者_StackOverflow) in some context and another thread continuously polling this entire context to see if it has any wait threads waiting for more than 5 minutes.


Set up a ScheduledExecutorService. Before acquiring the lock, schedule a task to fire in 5 minutes and keep the Future. When the lock is acquired, cancel the Future.

ScheduledExceutorService ses;
Future f = ses.schedule(new Runnable(){...}, 5, TimeUnit.Minutes);
lock.lock();
f.cancel();

If you acquire the lock before the submitted task has executed, it should be cancelled.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜