Java — java.util.concurrent.locks.ReentrantLock | Code Factory

  • It is the implementation class of Lock interface and it is the direct child class of Object.
  • Reentrant means a thread can aquire same lock multiple times without any issue.
  • Internally reentrant lock increments threads personal count whenever we call lock() method and decrement count value whenever thread calls unlock() method and lock will be released whenever count reached 0.
  • Creates an instance of ReentrantLock.
  • Creates an instance of ReentrantLock with the given fairness policy.
  • If the fairness is true then longest waiting thread can aquire the lock if it is available that is it follows FCFS (First Come First Serve) policy.
  • If the fairness is false then which waiting thread will get the chance we can’t expect.
  • Default vale for fairness is false.
  1. ReentrantLock rl = new ReentrantLock();
  2. ReentrantLock rl = new ReentrantLock(true);
  3. ReentrantLock rl = new ReentrantLock(false);
  4. All of the above
  • Acquires the lock.
  • Acquires the lock only if it is not held by another thread at the time of invocation.
  • Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted.
  • Acquires the lock unless the current thread is interrupted.
  • Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.
  • Attempts to release this lock.
  • Queries the number of holds on this lock by the current thread.
  • Returns true iff lock is hold by current thread.
  • Returns number of threads waiting for the lock.
  • Returns a collection of threads which are waiting to get the lock.
  • Returns true if any thread waiting to get the lock.
  • Returns true if lock is aquired by some thread.
  • Returns true if fairness policy is set with the true value.
  • Returns the thread which aquires the lock.
package com.example.thread;import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockTest {
public static void main(String... args) {
ReentrantLock rl = new ReentrantLock();
rl.lock();
rl.lock();
System.out.println(rl.isLocked()); // true
System.out.println(rl.isHeldByCurrentThread()); // true
System.out.println(rl.getQueueLength()); // 0
rl.unlock();
System.out.println(rl.getHoldCount()); // 1
System.out.println(rl.isLocked()); // true
rl.unlock();
System.out.println(rl.isLocked()); // false
System.out.println(rl.isFair()); // false
}
}
package com.example.thread;import java.util.concurrent.locks.ReentrantLock;/**
* @author code.factory
*
*/
public class ReentrantLockTest {
public static void main(String... args) {
Display d = new Display();
MyThread t1 = new MyThread(d, "Narendra");
MyThread t2 = new MyThread(d, "Yogi");
t1.start();
t2.start();
}
}
class Display {
ReentrantLock rl = new ReentrantLock();
public void wish(String name) {
rl.lock(); // #1
for(int i=0; i<5; i++) {
System.out.print("Good Morning ");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(name);
}
rl.unlock(); // #2
}
}
class MyThread extends Thread {
Display d;
String name;

public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}

public void run() {
d.wish(name);
}
}
Good Morning Narendra
Good Morning Narendra
Good Morning Narendra
Good Morning Narendra
Good Morning Narendra
Good Morning Yogi
Good Morning Yogi
Good Morning Yogi
Good Morning Yogi
Good Morning Yogi
  • If we comment lines #1 and #2 then the thread will be executed simultaneously and we will get irregular output. If we are not commenting lines #1 and #2 then the thread will be executed one by one and we will get regular output.
package com.example.thread;import java.util.concurrent.locks.ReentrantLock;/**
* @author code.factory
*
*/
public class ReentrantLockTest {
public static void main(String... args) {
MyThread t1 = new MyThread("First Thread");
MyThread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
static ReentrantLock rl = new ReentrantLock();
public MyThread(String name) {
super(name);
}

public void run() {
if(rl.tryLock()) {
System.out.println(Thread.currentThread().getName() + " get lock");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
rl.unlock();
} else {
System.out.println(Thread.currentThread().getName() + " unable to get lock");
}
}
}
First Thread get lock
Second Thread unable to get lock
package com.example.thread;import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author code.factory
*
*/
public class ReentrantLockTest {
public static void main(String... args) {
MyThread t1 = new MyThread("First Thread");
MyThread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
static ReentrantLock rl = new ReentrantLock();
public MyThread(String name) {
super(name);
}

public void run() {
do {
try {
if(rl.tryLock(2000, TimeUnit.MILLISECONDS)) {
System.out.println(Thread.currentThread().getName() + " get lock");
Thread.sleep(5000);
rl.unlock();
System.out.println(Thread.currentThread().getName() + " release lock");
} else {
System.out.println(Thread.currentThread().getName() + " unable to get lock");
}
} catch(Exception e) {
e.printStackTrace();
}
} while(true);
}
}
Second Thread get lock
First Thread unable to get lock
First Thread unable to get lock
First Thread get lock
Second Thread release lock
Second Thread unable to get lock
Second Thread unable to get lock
First Thread release lock
Second Thread get lock
First Thread unable to get lock
First Thread unable to get lock
First Thread get lock
Second Thread release lock
Second Thread unable to get lock
Second Thread unable to get lock
.
.
.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Joomla — What is it — What is it Used For

[Part 1] The Best Alternatives to Expensive Bootcamps (Comprehensive Free & Pay-Once-You-Get-A-Job…

TRON Developer Guide — TRON-CLI

Work smart, not hard — Part 1

Meet Our New Senior VP of Engineering: Former GOAT CTO Andy Shin!

Considering a career in tech? Start here.

How and Why I Became AWS Certified

Royal Q Software Review: Can You Make Money? [Pros & Cons]

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Explore Prototype Design Pattern

SOLID Principles in Java

Evolving the State Design Pattern

Strategy Pattern — java — get the gist of it in 2 min.