Reentrantlock Java
By AmarSivas | | Updated : 2021-03-12 | Viewed : 8054 times

The reentrant Lock mechanism is one of the techniques to avoid data inconsistency in multi-threaded environments. It is introduced in java 1.5 in the package of java.util.concurrent. It is very useful in multi-threading.
Table of Contents:
Quick note for Lock in Java
The lock provides access control to thread exclusively on share resources to avoid access control on shared resources by other threads at the same time. A lock is the implementation of the Lock interface which in the package
Reentrant Lock in Java
Reentrant Lock Example
package com.docsconsole.locks.example1;
import java.util.concurrent.locks.ReentrantLock;
public class CounterWithReentrantLock {
private final ReentrantLock lock = new ReentrantLock();
private int counter = 0;
public int getCount() {
lock.lock();
try {
String currentThreadName = Thread.currentThread().getName();
System.out.println("Current Thread"+ currentThreadName + " counter: " + counter);
return counter ++;
} finally {
lock.unlock();
}
}
public static void main(String args[]) {
final CounterWithReentrantLock counter = new CounterWithReentrantLock();
Thread t1 = new Thread() {
@Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace(); }
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}