How is Java Lock better than Synchronization

Here are few benefits of using Java’s Lock API over Synchronization

1.Java Lock API 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.

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *