ReentrantLock
can be used for timeout requirements. Suppose you are trying to acquire a lock but the lock is already taken at that point of time you can use tryLock()
which will return immediately and later you can try again.
ReentrantLock
has some other advantage of being provide fairLock or unFair by its con structure:
public ReentrantLock(boolean fair)
if you put the fair
as false
than it will not provide you a lock with fair ordering. And unfair ordering out performs the fair lock. I can explain this if you need more details.
But the problem with ReentrantLock
is, it is hard to debug because in the logs it can't explain about the owner of the lock but in synchronized it is possible. It's the biggest disadvantage.
you can implement features like dining philosopher with this locking mechanism. If both sticks are available than go ahead and eat else drop the one which you are currently holding.
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (l.getLeftLock().tryLock()) {
try {
if (r.getRightLock().tryLock()) {
try {
System.out.println("Eating philosopher1 !!!!");
} finally {
r.getRightLock().unlock();
}
}
} finally {
l.getLeftLock().unlock();
}
}
try {
Thread.currentThread().sleep((int) (100 * Math.random()));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}