[concurrency-interest] Waiting for object value to be available.

Tim Peierls tim at peierls.net
Tue Aug 23 14:21:27 EDT 2005

Peter Veentjer - Anchor Men wrote:
> I allready had removed the read write lock ...
> public class Bar<E> {
>  private final ReentrantLock _lock;
>  private volatile E _item;
>  private final Condition _availableCond;
>  public Bar(boolean fair){
>   _lock = new ReentrantLock(fair);
>   _availableCond = _lock.newCondition();
>  }
>  public E get() throws InterruptedException {
>   _lock.lockInterruptibly();
>   try{
>    while(_item == null)
>     _availableCond.wait();
>    return _item;
>   }finally{
>    _lock.unlock();
>   }
>  }
>  public void set(E item) throws InterruptedException {
>   _lock.lockInterruptibly();
>   try{
>    _item = item;
>    if(_item!=null)
>     _availableCond.signalAll();
>   }finally{
>    _lock.unlock();
>   }
>  }
> }

Your version doesn't take advantage of the volatility of _item. You should 
either remove the volatile keyword or add these lines to the top of your get() 

     E item = _item;
     if (item != null) return item;

Also, do you have any experimental evidence to suggest that the Lock will ever 
need to be fair? It seems unlikely to me, especially if you add the volatile 
optimization above, where readers don't even block when there's a non-null value.

And since there won't be much blocking, there won't be much lock contention, 
so you don't really need to use ReentrantLock at all. Stick with intrinsic 
locking, as in the SimpleAwaitableValue code I posted.

ReentrantLock is appropriate when you need a feature that it provides that 
intrinsic locking doesn't or when you expect a *lot* of contention. Otherwise, 
intrinsic locking is easier to read and likely to perform just as well, if not 

> But I`m going to need the read write lock. I don`t want multiple 
> values of the WaitableValue out there.. only one is allowed
> (I only want one task-instance running, not two).. So I`m going
> to use the read write lock to garantuee that all old values
> are returned before a new value is available.

Using RWL doesn't prevent two readers from seeing different values if there is 
an intervening write, so I don't think you need it.


More information about the Concurrency-interest mailing list