[concurrency-interest] ReadWriteLocks and Conditions

Peter Veentjer alarmnummer at gmail.com
Mon Feb 5 09:40:17 EST 2007

I'm working on a structure called the LendeableReference. This
structure makes it possible to lend a reference to multiple threads
(values are taken from the LendableReference) and after a thread is
done with the reference, it takes it back so that a new reference can
be set. If no reference is available, taking threads block until a
reference is available.

I'm using a ReadWriteLock: when a value is taken the readlock is
locked, when it is takenback, the readlock is released. And when a new
value is set, a writelock needs to be obtained first (all readlocks
need to be returned first), the value is set, and the writelock is
released, and readers are now able to obtain readlocks again.

So this is how it should work. The problem is the waitingpart of the
takes. If there are two threads that want to take a value, one of the
takers doesn't return immediately. I understand why it happens (one of
the takers has the readlock at the end, so the second taker can't
obtain the writelock). But what is the correct way to implement the
waiting logic? I have looked at the documentation of the ReadWriteLock
and the ReentrantReadWriteLock, but I haven't figured out a way to
solve this problem.

This is the code of the take.

 public E take() throws InterruptedException {
        if(ref != null){
            return ref;



            while (ref == null)
            return ref;

And the refAvailableCondition is a Condition made by the writelock.

More information about the Concurrency-interest mailing list