Question

My understanding of the RentrantReadWriteLock is that it allows many reads at the same time but only one write.

When we try to acquire a read lock the doc states

Acquires the read lock if the write lock is not held by another thread and returns immediately.

If the write lock is held by another thread then the current thread becomes disabled 
for thread scheduling purposes and lies dormant until the read lock has been acquired.

what does held here mean?

  • Another thread has requested a write lock and is executed than write?

or

  • The above and the case when another thread has requested a write lock but is waiting to get it.

Because when a write lock is requested it is not granted if

  • Someone else has a write lock
  • Somebody else has a read lock

From write lock doc:

Acquires the write lock if neither the read nor write lock are held by another 
thread and returns immediately, setting the write lock hold count to one.

...

If the lock is held by another thread then the current thread becomes 
disabled for thread scheduling purposes and lies dormant until the write lock has 
been acquired, at which time the write lock hold count is set to one.

So when a thread is waiting for a write lock after requesting it, I just want to get an idea of subsequent behaviour of invocations for read locks. Do they make the request for the write lock wait even longer or not?

Was it helpful?

Solution

Held in this context means that the lock has been requested and provided. It is not considered held if you are just waiting for it.

There are known issue with the ReentrantReadWriteLock when a large number of threads are requesting locks. Dr. Heinz Kabutz produced an interesting newsletter on lock starvation with them.

I understand many of these issues have been fixed with the new Java 7 Phaser but I am not yet sufficiently familliar with it to say one way or the other.

OTHER TIPS

what does held here mean?

lock has been requested AND acquired.

So when a thread is waiting for a write lock after requesting it, I just want to get an idea of subsequent behaviour of invocations for read locks. Do they make the request for the write lock wait even longer or not?

If at some stage all your read locks have been released a call to lock.writeLock().lock() will succeed in acquiring the write lock. Note however that more than one thread can hold the read lock - so if you have one thread or more holding the read lock at all time, no other thread will be able to acquire the write lock and you will have a serious liveness issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top