What is Reentrantlock In Java?

By | March 7, 2023

ReentrantLock is a class in Java that provides a way to create a mutually exclusive locking mechanism for threads. It allows multiple threads to access a shared resource, but only one thread can access it at a time. It is a more advanced alternative to the synchronized keyword in Java.

Here’s an example of how to use ReentrantLock in Java:

import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
private ReentrantLock lock = new ReentrantLock();
private int count = 0;

public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}

public int getCount() {
return count;
}
}

In this example, we have a class called LockExample with a shared variable called count. The increment method increments the count variable in a thread-safe manner using ReentrantLock. The lock() method is called to acquire the lock, and the unlock() method is called to release the lock once the critical section has been executed.

Here’s an example of how to use the LockExample class:

public class Main {
public static void main(String[] args) throws InterruptedException {
LockExample lockExample = new LockExample();

Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
lockExample.increment();
}
});

Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
lockExample.increment();
}
});

thread1.start();
thread2.start();
thread1.join();
thread2.join();

System.out.println(lockExample.getCount());
}
}

In this example, we create two threads that call the increment method of the LockExample class 10,000 times each. We then wait for the threads to finish using the join() method and print the final value of the count variable.

Note that the ReentrantLock class provides additional functionality compared to the synchronized keyword, such as the ability to interrupt a thread waiting for a lock, condition variables, and the ability to specify whether a lock is fair or not. However, with added functionality comes added complexity, so it’s important to use ReentrantLock only when necessary and understand its behavior thoroughly.

Leave a Reply

Your email address will not be published. Required fields are marked *