What is the ReentrantLock#tryLock(long,TimeUnit) implementation doing when it tries to aquire a lock ? Assume Thread A acually owns the Lock of myLock, and Thread B call myLock.tryLock(10,SECONDS), is Thread B sleeping or waiting ?
In other words, was is the difference of this 2 implementations:
1.
while (true)
try {
if (readLock.tryLock())
return;
MILLISECONDS.sleep(5);
}catch (InterruptedException e) {}
2.
while (true)
try {
if (readLock.tryLock(5,MILLISECONDS))
return;
}catch (InterruptedException e) {}
First of all, the second will wait less than 5 millis if lock released, because it doesn’t need wait for wake up from the
sleep. So, it’s less exposed to starvation problem.Then,
j.u.c.lpackage uses LockSupport#park methods to pause a thread, notThread.sleep. And as I understand it makes difference on the thread scheduler, theparkallows lower latency, but not sure how exactly thesleepis implemented.Also, your code doesn’t make any sense, exactly the same effect could be achieved by
lock()method.