Synchronized and limitation
Synchronized keyword doesn't support fairness
A thread can be blocked waiting for lock, for an indefinite
period of time and there was no way to control that.
Lock interface provide opportunity of acquiring lock by different
* if we are using lock() and the lock is not available the current
thread will be suspended until the lock will be released;
* lockInterruptible() method acquires the lock until the
current thread will be interrupted or lock will be released;
* tryLock() method acquires the lock only if it is available at
the time of invocation (non-blocking, not waiting for the lock
will be released);
* If we want to acquire the lock interruptibly with the specified
waiting timeout we should use tryLock(long timeout,
TimeUnit timeUnit) method.
* There is only one method for unlocking the lock: unlock()
and it works as it named.
Main Differences Between Locks and
* A synchronized block makes no guarantees about the
sequence in which threads waiting to entering it are granted
* You cannot pass any parameters to the entry of a
synchronized block. Thus, having a timeout trying to get
access to a synchronized block is not possible.
* The synchronized block must be fully contained within a
single method. A Lock can have it's calls to lock() and
unlock() in separate methods
What is ReentrantLock in Java
On class level, ReentrantLock is a concrete
implementation of Lock interface provided in Java
concurrency package from Java 1.5 onwards.
Thread can acquire the same lock multiple times without
Reentrant locking increments special thread-personal
counter (unlocking - decrements) and the lock will be
released only when counter reaches zero.
ReentrantLock is mutual exclusive lock,
Two events are 'mutually exclusive' if they cannot occur at
the same time.
Benefits of ReentrantLock in Java
1) Ability to lock interruptibly.
2) Ability to timeout while waiting for lock.
3) Power to create fair lock.
4) API to get list of waiting thread for lock.
5) Flexibility to try for lock without blocking.