Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ReentrantLock#tryLock(long,TimeUnit) doing when it tries to aquire the lock?

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) {}
like image 329
Chriss Avatar asked Dec 06 '11 10:12

Chriss


People also ask

What is ReentrantLock in Java?

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.

Why is ReentrantLock needed?

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.

What is the difference between lock and ReentrantLock?

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.

What is the difference between synchronized keyword and ReentrantLock?

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.


1 Answers

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.

like image 123
kan Avatar answered Sep 29 '22 10:09

kan