Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fair locking in ReeantrantReadWriteLock

In Java Concurrency In Practice by B. Goetz, section 13.5 said:

In Java 5.0, the read lock behaves more like a semaphore than a lock, maintaining only the count of active readers, not their identities. The behavior was changed in Java 6 to keep track also of which threads have been granted the read lock6.

6 One reason for this change is that under java 5.0, the lock implementation cannot distinguish between a thread requesting the read lock for the first time and reentrant lock request, which would make fair read-write lock deadlock-prone.

My question is what's wrong with fairness? Why was the unfair read-write lock shielded from the deadlock?

Could you explain what he meant? I mean in which circumstances does a fair read-write lock under Java 5 cause a deadlock? And if it behaved like a Semaphore why didn't the fair Semaphore cause a deadlock?


1 Answers

If the implementation does not know whether a requesting thread already has the lock, in case of a fair locking strategy new request from the same thread would be queued after prior requests, possibly from other threads.

If there are write requests from other threads preceding this reentrant request, they cannot advance since the thread holding the lock is also blocked waiting for its reentrant request. Resulting in deadlock.

An unfair locking strategy does not suffer from this problem as the reentrant request can jump the queue (barging) and doesn't need to wait for prior requests.

Semaphore does not suffer from this problem because it is not meant to be reentrant.

like image 99
bowmore Avatar answered May 01 '26 06:05

bowmore