views:

146

answers:

2

Just a quick question about ReadWriteLocks in Java (specifically the ReentrantReadWriteLock implementation) as I don’t find the sun documentation clear.

What happens if a read lock is held by a thread when a write lock is requested by another? Does the write lock thread have to wait for all currently held read-locks to be released? Also, do all new read-lock requests get blocked until the write-lock is granted and released?

Thanks

+1  A: 

A ReadWriteLock cannot have a write lock held at the same time as read locks. Requests for, say, a write lock when a read lock is held will result in blocking or a fail.

Tom Hawtin - tackline
+2  A: 

The Javadoc explains this:

This class does not impose a reader or writer preference ordering for lock access. However, it does support an optional fairness policy. When constructed as fair, threads contend for entry using an approximately arrival-order policy. When the write lock is released either the longest-waiting single writer will be assigned the write lock, or if there is a reader waiting longer than any writer, the set of readers will be assigned the read lock. When constructed as non-fair, the order of entry to the lock need not be in arrival order. In either case, if readers are active and a writer enters the lock then no subsequent readers will be granted the read lock until after that writer has acquired and released the write lock.


What happens if a read lock is held by a thread when a write lock is requested by another? Does the write lock thread have to wait for all currently held read-locks to be released?

Yes, the writer will have to wait. But it will only wait for the currently held read locks. Any readers arriving later will queue after the writer.

Also, do all new read-lock requests get blocked until the write-lock is granted and released?

Yes

Thilo