In this article, we will explain intrinsic locks in Java for fairness strategy. The lockInterruptibly() locks the lock unless the thread calling the method has been interrupted.
lock()
lockInterruptibly()
tryLock()
tryLock(timeout, timeUnit)
unlock()
The various method allows making programming easier.
ReentrantReadWriteLock is mostly used for using reading and writing to a resource. It maintains a pair of associated locks one for read-only operations and one for writing. The advantage is that read lock allows multiple threads to access at the same time, provided write lock has not acquired it first. Whereas a write lock is exclusive.
While creating a lock it accepts an optional fairness parameter when set true to grant access to the longest waiting thread.
The tryLock() backs out after the expiry gives the advantage to take action in terms of system hangs up.
lockInterruptibly() backout if another thread interrupts it.
Example:
private final ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock();
final Lock rl = rw1.readLock();
final Loc wl = rw1.writeLock();
Now in your code you can simply use both read and write locks separately.
public Object readExample() {
rl.Lock()
//Do reading here
rl.unLock()
}
public void writeExample(…) {
wl.Lock();
//do writing here
wl.unLock();
}
The locking mechanism is simplified and becomes an integral part of the multi-threading application. Multi-Threading is complicated and used with great care to avoid race-conditions, deadlock and live lock.
Please visit Business Integration Software to see various products using locking and synchronization.
Assessment Management Software
Multiple Choice Question Software