[Synchronization - Java] Reentrant Locks vs Synchronized
1) Reentrant Lock
- Implementation of Lock interface.
- Mutually-exclusive lock (similar to synchronized) with extended feature like fairness.
- Lock is acquired via lock() and is held until unlock()
2) Reentrant Lock vs Synchronized
2.1) Blocking Indefinitely vs Temporarily/Selectively.
Main difference is reentrant lock has the ability to try to lock interruptibly and with timeout. tryLock() allows program to try the lock without being blocked. In summary, Thread doesn't need to blocked indefinitely, whereas synchronized block block indefinitely.
2.2) Fairness
Supported by Reentrant lock, but not by synchronized.
2.3) Get List of Threads waiting for Lock
Reentrant locks have ability to see all threads waiting on the lock; accessible via API.
4) Example
Code example below contains lock version (getCount()) and Synchronized version (getCountTwo()); it's obvious synchronized version is more neat and less prone to error.
3) Cons of Reentrant Lock
3.1) Readability
Requires wrapping in try-finally block, which makes code unreadable and hides business logic.3.2) Potential Bugs
Programmer is now responsible for acquiring and releasing lock, which is a power but also opens the possibility to bugs; eg. when programmer forgets to release lock in finally block.4) Example
Code example below contains lock version (getCount()) and Synchronized version (getCountTwo()); it's obvious synchronized version is more neat and less prone to error.
Comments
Post a Comment