Member-only story
Java Multithreading, Concurrency, and Parallelism — Part 15
ReentrantLocks and Fairness Continued.,
We have seen the Lock
interface and its implementation class ReentrantLock
in Part-14. Now in this part, we will see ReentrantLock
in more detail. We will see the other methods that this API offers, and then we will compare the performance comparisons between fairness and non-fairness. Here are the methods below from theLock
interface.
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long timeout, TimeUnit unit) throws
InterruptedException;
void unlock();
Condition newCondition();
}
We have already specified that ReenetrantLock
implements all these methods and provides us the same mutual exclusion semantics and memory-visibility guarantees as synchronized
. And we have also seen that we need to go withReentrantLocks
for more flexible locking mechanisms and the implementation of Counter
using ReentrantLock
. Here we will see more examples and how we can use ReentrantLock
.
We will now see the other variant of lock()
method — the tryLock()
. The tryLock()
is overloaded — two flavors: One with timeout and the other without.
tryLock()
is very useful in writing the code avoiding the deadlocks which are very fatal with the intrinsic locks provided by synchronized
. With these two flavors of tryLock()
method, we can implement the techniques like…