I have a thread that's running in infinite loop executing some code, which will acquire a Lock.
Meanwhile I have another thread doing scheduled task that also need to acquire the lock to do something.
To ensure that the scheduled task won't be starved in case the lock is occupied by the infinite loop for too long, I let the thread sleep for a moment after unlocking. I think that's a reasonable move and not an overkill provided that I don't mind the performance cost with the sleep?
And a follow up question too: I see someone else doing the same, but instead of sleeping for a constant time, it's sleeping for a random time ThreadUtil.sleep(RandomUtil.nextInt(5, 100))
, but I couldn't fathom the benefits of doing this.
private final Lock writeLock = new ReentrantLock(true);
while (true) {
writeLock.tryLock(100, TimeUnit.MILLISECONDS);
try {
doSomething();
} finally {
writeLock.unlock();
}
// food for everyone!
ThreadUtil.sleep(10);
}
Some points to clarify and a follow up question:
- The scheduled task is acquiring the lock with a timeout (
writeLock.tryLock(100, TimeUnit.MILLISECONDS)
), identical to how the infinite-loop thread does it. - In addtion to the scheduled task, there's actually another use case to trigger a function manually (via ws call) and acquire the lock to do something.
- The question: if the infinite loop thread does NOT sleep at all, I assume other threads will still eventually be executed, just that there might be a delay of uncertain amount of time?