Why does java.util.concurrent.ArrayBlockingQueue use 'while' loops instead of 'if' around calls to

Posted by theFunkyEngineer on Stack Overflow See other posts from Stack Overflow or by theFunkyEngineer
Published on 2010-06-02T18:44:39Z Indexed on 2010/06/02 18:54 UTC
Read the original article Hit count: 87

Filed under:
|
|

I have been playing with my own version of this, using 'if', and all seems to be working fine. Of course this will break down horribly if signalAll() is used instead of signal(), but if only one thread at a time is notified, how can this go wrong?

Their code here - check out the put() and take() methods; a simpler and more-to-the-point implementation can be seen at the top of the JavaDoc for Condition.

Relevant portion of my implementation below.

public Object get()
{
    lock.lock();
    try 
    {
        if( items.size() < 1 )
            hasItems.await();
        Object poppedValue = items.getLast();
        items.removeLast();
        hasSpace.signal();
        return poppedValue; 
    } catch (InterruptedException e) {
        e.printStackTrace();
        return null;
    } 
    finally
    {
        lock.unlock();
    }
}

public void put(Object item)
{
    lock.lock();
    try 
    {
        if( items.size() >= capacity )
            hasSpace.await();
        items.addFirst(item);
        hasItems.signal();
        return;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } 
    finally
    {
        lock.unlock();
    }
}

P.S. I know that generally, particularly in lib classes like this, one should let the exceptions percolate up.

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading