Thursday 12 May 2016

Advantages and Disadvantages of Lock in Java

Advantages of ReentrantLock in Java

1) Ability to timeout while waiting for lock using Lock.tryLock(long timeout, TimeUnit timeUnit).

2) Ability to lock interruptibly.
The lockInterruptibly method allows you to try to acquire a lock while remaining responsive to interruption. lockInterruptibly() may block if the lock is already held by another thread and will wait until the lock is acquired. This is the same as with regular lock(). But if another thread interrupts the waiting thread lockInterruptibly() will throw InterruptedException.

3) Power to create fair lock i.e. longest waiting thread gets the lock first.

4) API to get list of waiting thread for lock.

5) Flexibility to try for lock without blocking.

Disadvantages of ReentrantLock in Java

Drawback of using ReentrantLock is wrapping method body inside try-finally block, which makes code unreadable and hides business logic because finally is required to call unlock method.

In case of lock, programmer is responsible for acquiring and releasing lock, it may lead to subtle bugs when programmer forget to release the lock in finally block.


12 comments:

  1. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Mobile Locksmith Overland Park

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...