javamultithreadinglockingreentrantlock

Never ending read request.! Reentrant Lock


While writing a piece of code for work I have encountered a use case for ReentrantReadWriteLock. So far my understanding is as long as there are more than zero thread with read lock a thread cannot acquire write lock. Application I am working on is read heavy with very less writes. Is it possible that more than zero thread will always have a read lock acquired and if a thread requires a write lock it will forever be suspended?


Solution

  • This is known as "writer starvation".

    When looking at the Javadoc for ReentrantReadWriteLock, we can find the following paragraphs:

    This class does not impose a reader or writer preference ordering for lock access. However, it does support an optional fairness policy.

    Non-fair mode (default) When constructed as non-fair (the default), the order of entry to the read and write lock is unspecified, subject to reentrancy constraints. A nonfair lock that is continuously contended may indefinitely postpone one or more reader or writer threads, but will normally have higher throughput than a fair lock.

    Fair mode 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.

    A thread that tries to acquire a fair read lock (non-reentrantly) will block if either the write lock is held, or there is a waiting writer thread. The thread will not acquire the read lock until after the oldest currently waiting writer thread has acquired and released the write lock. Of course, if a waiting writer abandons its wait, leaving one or more reader threads as the longest waiters in the queue with the write lock free, then those readers will be assigned the read lock.

    A thread that tries to acquire a fair write lock (non-reentrantly) will block unless both the read lock and write lock are free (which implies there are no waiting threads). (Note that the non-blocking ReentrantReadWriteLock.ReadLock.tryLock() and ReentrantReadWriteLock.WriteLock.tryLock() methods do not honor this fair setting and will immediately acquire the lock if it is possible, regardless of waiting threads.)

    In short: If you don't specify that the ReentrantReadWriteLock uses a fair policy, that can happen