Sunday, June 9, 2019

Lock Interface In Concurrency API

Q- What is lock in java?
A lock is a thread synchronization mechanism like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks.

Lock interface:  Lock interface is present in java.util.concurrent.locks package
ReentrantLock: ReentrantLock is a class which implements the Lock interface and provides synchronization to methods while accessing shared resources.
  • void lock()
  • void unlock()
  • boolean tryLock() 
  • boolean tryLock(long timeout, TimeUnit timeUnit) 
  • void lockInterruptibly() 
  • getHoldCount():
  • isHeldByCurrentThread():
  Lock implementations  
ReentrantLock class implements the Lock interface.

  ReadWriteLock interface  
  • Lock readLock() – returns the lock that’s used for reading
  • Lock writeLock() – returns the lock that’s used for writing
ReentrantReadWriteLock: ReentrantReadWriteLock class implements the ReadWriteLock interface.
  • Read Lock – if no thread acquired the write lock or requested for it then multiple threads can acquire the read lock
  • Write Lock – if no threads are reading or writing then only one thread can acquire the write lock

ReadWriteLock lock = new ReentrantReadWriteLock();
Lock writeLock = lock.writeLock();
Lock readLock = lock.readLock();

  StampedLock  
StampedLock is introduced in Java 8. It also supports both read and write locks.

  Conditions  
The Condition class provides the ability for a thread to wait for some condition to occur while executing the critical section.

ReentrantLock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition1 = lock.newCondition();
 
Related Tutorials

No comments:

Post a Comment