What is ReentrantLock in Java?

ReentrantLock is a synchronization aid that allows threads to lock and unlock a specific resource. It belongs to the java.util.concurrent.locks package and provides more advanced locking mechanisms than the traditional synchronized block. With ReentrantLock, a thread can reacquire the lock that it already holds, which prevents deadlocks and improves concurrency in multi-threaded environments.

Here’s an example of how to use ReentrantLock:

import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockExample { private final ReentrantLock lock = new ReentrantLock(); public void exampleMethod() { lock.lock(); // Acquire the lock try { // Critical section System.out.println("Lock is held by " + Thread.currentThread().getName()); // Perform some operations } finally { lock.unlock(); // Release the lock } } } public class Main { public static void main(String[] args) { ReentrantLockExample example = new ReentrantLockExample(); Thread thread1 = new Thread(example::exampleMethod); Thread thread2 = new Thread(example::exampleMethod); thread1.start(); thread2.start(); } }

ReentrantLock Java concurrency synchronization multi-threading locking mechanisms