Java MCQ: Which class in Java provides a mechanism for creating reentrant locks?
Answer:
Explanation:
The ReentrantLock
class in Java provides a mechanism for creating reentrant locks. It is part of the java.util.concurrent.locks
package and is used as an alternative to the synchronized
keyword for managing thread synchronization.
A reentrant lock allows a thread to acquire the same lock multiple times without causing a deadlock. If the same thread already holds the lock, it can re-enter the lock without blocking, provided it releases the lock the same number of times it was acquired.
Here’s an example of using ReentrantLock
:
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
public void performTask() {
lock.lock();
try {
System.out.println("Task performed by " + Thread.currentThread().getName());
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLockExample example = new ReentrantLockExample();
Thread t1 = new Thread(example::performTask);
Thread t2 = new Thread(example::performTask);
t1.start();
t2.start();
}
}
In this example, the ReentrantLock
is used to ensure that only one thread can execute the performTask()
method at a time. The lock()
method acquires the lock, and the unlock()
method releases it. The finally
block ensures that the lock is always released, even if an exception occurs.
ReentrantLock
offers more advanced features than the synchronized
keyword, such as the ability to interrupt threads waiting for the lock, try to acquire the lock without blocking, and implement fair locking policies.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html