Junior — Middle
Explain what ReentrantLock is and how it differs from standard synchronization mechanisms in Java.
sobes.tech AI
Answer from AI
ReentrantLock is a class from the java.util.concurrent.locks package that implements a lock mechanism with the possibility of re-acquisition (reentrant). This means that a thread that has already acquired the lock can do so again without blocking itself.
Differences from the standard synchronized:
- Flexibility: ReentrantLock allows explicitly acquiring and releasing the lock using lock() and unlock() methods, whereas synchronized works through blocks or methods.
- Interruptibility: You can attempt to acquire the lock with the possibility of interruption (lockInterruptibly()), which is not available with synchronized.
- Attempt to acquire without waiting: tryLock() allows attempting to acquire the lock and immediately getting a result without blocking.
- Condition support: ReentrantLock supports Condition objects for more fine-grained waiting and notification.
Example of using ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}