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

Peter Veentjer - Anchor Men p.veentjer at anchormen.nl
Tue Aug 23 17:14:03 EDT 2005

Your version doesn't take advantage of the volatility of _item. 
Btw: If I don`t add the volatile keyword, the item in the while loop could be a cached value and that value could never update. So or something has changed in Java (and Java has changed their memory/concurrency model), or I`m missing something.. (or you made a mistake).
the code:
  public E get() throws InterruptedException {
>   _lock.lockInterruptibly();
>   try{
>    while(_item == null)
>     _availableCond.wait();
>    return _item;
>   }finally{
>    _lock.unlock();
>   }
>  }

It _item is not made volatile, the while loop could use some value stored in some kind of cpu-register that never gets updated. That is as far as I know of, the whole reason about the existence of the volatile keyword.
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