I don't understand the difference between them. I thought a lock from the lock interface was reentrant too then what's the difference between them? When would you use each?
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
Major difference between lock and synchronized: with locks, you can release and acquire the locks in any order. with synchronized, you can release the locks only in the order it was acquired.
In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock.
boolean tryLock() – This is a nonblocking version of lock() method. It attempts to acquire the lock immediately, return true if locking succeeds. boolean tryLock(long timeout, TimeUnit timeUnit) – This is similar to tryLock(), except it waits up the given timeout before giving up trying to acquire the Lock.
Lock
is an interface. It defines a set of methods that all locks should have.
ReentrantLock
is a concrete class that implements the Lock
interface. It implements all the methods defined in Lock
, plus much more. Additionally, as mentioned in the name, the lock is re-entrant which means the same thread can acquire the lock as many times as it wants. This is essentially the same behavior as the native object monitor locks provided by the synchronized
keyword.
The Lock
interface makes it possible for you to implement your own kind of lock. For example, you might design a lock that issues an HTTP request (performing network I/O) to lock a remote resource. Another class that uses your lock wouldn't care about the internal details of your lock; it only cares that your custom lock respects the Lock
interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With