

package gov.va.med.cds.work;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import commonj.work.WorkEvent;
import commonj.work.WorkException;
import commonj.work.WorkItem;


public class WorkQueue
{

    private final BlockingQueue<WorkItem> workQueue;

    public WorkQueue( )
    {
        workQueue = new LinkedBlockingQueue<WorkItem>();
    }


    public DefaultWorkItem getWork( ) throws WorkException
    {
        try
        {
            //return ( DefaultWorkItem )workQueue.take(); // blocks if empty
            //return null after waiting for 1 microsecond
            return ( DefaultWorkItem )workQueue.poll(1, TimeUnit.MICROSECONDS); 
        }
        catch ( InterruptedException e )
        {
            throw new WorkException( e );
        }
    }


    public void addWork( WorkItem workItem ) throws WorkException
    {
        try
        {
            workQueue.put( workItem );
        }
        catch ( InterruptedException e )
        {
            ( ( DefaultWorkItem )workItem ).setStatus( WorkEvent.WORK_REJECTED);
            throw new WorkException( e.getMessage() );
        }
    }
}