Lock Interface in Java


Published on

This document gives detail review about Lock interface in Java

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

Lock Interface in Java

  1. 1. Lock Interface
  2. 2. Synchronized and limitation   Synchronized keyword doesn't support fairness A thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that.
  3. 3. Lock Interface Lock interface provide opportunity of acquiring lock by different ways: * if we are using lock() and the lock is not available the current thread will be suspended until the lock will be released; * lockInterruptible() method acquires the lock until the current thread will be interrupted or lock will be released;
  4. 4. continue... * tryLock() method acquires the lock only if it is available at the time of invocation (non-blocking, not waiting for the lock will be released); * If we want to acquire the lock interruptibly with the specified waiting timeout we should use tryLock(long timeout, TimeUnit timeUnit) method. * There is only one method for unlocking the lock: unlock() and it works as it named.
  5. 5. Main Differences Between Locks and Synchronized Blocks * A synchronized block makes no guarantees about the sequence in which threads waiting to entering it are granted access.  * You cannot pass any parameters to the entry of a synchronized block. Thus, having a timeout trying to get access to a synchronized block is not possible.   * The synchronized block must be fully contained within a single method. A Lock can have it's calls to lock() and unlock() in separate methods
  6. 6. What is ReentrantLock in Java On class level, ReentrantLock is a concrete implementation of Lock interface provided in Java concurrency package from Java 1.5 onwards. Thread can acquire the same lock multiple times without any issue. Reentrant locking increments special thread-personal counter (unlocking - decrements) and the lock will be released only when counter reaches zero. ReentrantLock is mutual exclusive lock, Two events are 'mutually exclusive' if they cannot occur at the same time.
  7. 7. Benefits of ReentrantLock in Java 1) Ability to lock interruptibly. 2) Ability to timeout while waiting for lock. 3) Power to create fair lock. 4) API to get list of waiting thread for lock. 5) Flexibility to try for lock without blocking.