To put it short,my question is,what are the advantages of using Lock and Condition in java in place of synchronized keyword,Lock seems to be more error prone to me.
-
Could you expand on why you think that? – awksp May 19 '14 at 20:43
-
I already had a look at that actually,but could not find the specific advantages of lock and condition from it. – KKGanguly May 19 '14 at 20:57
-
`ReadWriteReentrantLocks` can do things that `synchronized` blocks cannot do. Just like everything else in programming, there's a right time for everything – awksp May 19 '14 at 20:58
1 Answers
Lock vs synchronized
1. Lock provides more visibility and options for locking, unlike synchronized where a thread might end up waiting indefinitely for the lock, we can use tryLock() to make sure thread waits for specific time only.
2. Synchronization code is much cleaner and easy to maintain whereas with Lock we are forced to have try-finally block to make sure Lock is released even if some exception is thrown between lock() and unlock() method calls.
3. synchronization blocks or methods can cover only one method whereas we can acquire the lock in one method and release it in another method with Lock API.
4. synchronized keyword doesn’t provide fairness whereas we can set fairness to true while creating ReentrantLock object so that longest waiting thread gets the lock first.
5. We can create different conditions for Lock and different thread can await() for different conditions.
From here. For me, the most important reasons to use Lock are 3 and 4.

- 1,956
- 16
- 22