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.

1 comment:

  1. Amazing Article, thank you!. I am very glad to read your informative & practical blog. Kindly keep updating your blog. Java Developer is a wonderful career for IT students.To start Dream Career to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India .


Related Posts Plugin for WordPress, Blogger...