In Java, both ReentrantLock and synchronized keyword are used to provide mutual exclusion and synchronize access to shared resources among threads. However, there are some differences between them:
Locking mechanism: synchronized keyword is implemented as an implicit lock acquired by the executing thread while entering a synchronized block or method. On the other hand, ReentrantLock is implemented as an explicit lock object that is acquired and released by the thread explicitly.
Fairness: By default, synchronized keyword provides no fairness guarantee. In other words, there is no guarantee that the waiting threads will acquire the lock in the order they requested it. However, ReentrantLock can be configured to provide a fair locking policy where the longest-waiting thread gets the lock first.
Try locking: ReentrantLock provides a non-blocking tryLock() method that tries to acquire the lock and returns immediately without blocking the calling thread if the lock is not available. On the other hand, synchronized keyword does not provide any equivalent non-blocking mechanism.
Interruptible locking: ReentrantLock provides an lockInterruptibly() method that allows the thread to be interrupted while waiting to acquire the lock. On the other hand, synchronized keyword does not provide any equivalent interruptible mechanism.
Here’s an example code that illustrates the usage of ReentrantLock and synchronized keyword:
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private int count;
private final ReentrantLock lock = new ReentrantLock();
public synchronized void increment() {
count++;
}
public void incrementWithLock() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
In this example, increment() method is synchronized using the synchronized keyword. On the other hand, incrementWithLock() method uses ReentrantLock for synchronization. Both methods increment the shared count variable in a thread-safe way. The getCount() method returns the current value of count.