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) {}
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
2.1 Benefits of ReentrantLock in Java 1) Ability to lock interruptibly. 2) Ability to timeout while waiting for lock. 3) Power to create fair lock. 4) API to get list of waiting thread for lock.
Lock is an interface. It defines a set of methods that all locks should have. ReentrantLock is a concrete class that implements the Lock interface. It implements all the methods defined in Lock , plus much more.
In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock.
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.l
package uses LockSupport#park methods to pause a thread, not Thread.sleep
. And as I understand it makes difference on the thread scheduler, the park
allows lower latency, but not sure how exactly the sleep
is implemented.
Also, your code doesn't make any sense, exactly the same effect could be achieved by lock()
method.
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