Junior — Middle
Have you used the ReentrantLock mechanism in your projects for thread management?
sobes.tech AI
Answer from AI
Yes, ReentrantLock is an implementation of a lock with re-entry capability, used to control access to shared resources in multithreaded applications.
Differences from synchronized:
- You can attempt to acquire the lock with a timeout or without blocking (tryLock).
- It allows more flexible lock management (for example, unlocking in another method).
Example of using ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
ReentrantLock lock = new ReentrantLock();
public void safeMethod() {
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
}
Used ReentrantLock for managing concurrent access when more flexibility was needed than what synchronized provides.