Sunday, May 10, 2020

Java Concurrency using Read/Write Locking

This article talks about how to achive best performance in multi-threading application.
Issue with synchronised keyword:
-  If multiple threads are accessing an object for reading data, it does not make sense to use a synchronized block or any other mutually exclusive locks.
 - Thus it offers far less level of concurrency tha non-mutually exclusive.

ReentrantReadWriteLock is an implementation of the ReadWriteLock interface .

 1. Multiple Threads can acquire multiple read Locks, but only a single Thread can acquire mutually-exclusive write Lock .Other threads requesting readLocks have to wait till the write Lock is released. A thread is allowed to degrade from write lock to read lock but not vice-versa.

 ReentrantReadWriteLock()- Creates a new ReentrantReadWriteLock with default (nonfair) ordering properties.
ReentrantReadWriteLock(boolean fair)- Creates a new ReentrantReadWriteLock with the given fairness policy.

In addition, it allows a reader/writer thread acquire a read lock/write lock multiple times recursively (reentrancy).

Fair mode in ReentrantReadWriteLock
When constructed as fair, threads contend for entry using an approximately arrival-order policy. When the currently held lock is released, either the longest-waiting single writer thread will be assigned the write lock, or if there is a group of reader threads waiting longer than all waiting writer threads, that group will be assigned the read lock.

Lock downgrading in ReentrantReadWriteLock
ReentrantReadWriteLock also allows downgrading from the write lock to a read lock. You can first acquire a write lock, then the read lock and then release the write lock. So you are effectively left with a read lock. However, upgrading from a read lock to the write lock is not possible
Condition Support (on a write Lock only)
Allowing interruption on read as well as write Locks
Sample:
  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 try {
  readWriteLock.readLock().lock();
    // multiple readers can enter this section
    // if not locked for writing, and not writers waiting
    // to lock for writing.
        }
     finally {
        readWriteLock.readLock().unlock();
   }

try {
readWriteLock.writeLock().lock();
    // only one writer can enter this section,
    // and only if no threads are currently reading.
        }
} finally {
   readWriteLock.writeLock().unlock();
}

No comments:

Post a Comment