

package gov.va.med.cds.work;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import commonj.work.Work;
import commonj.work.WorkEvent;
import commonj.work.WorkException;


public class Worker
{

    private transient final WorkQueue workQueue;
    private transient final ExecutorService threadPool = Executors.newCachedThreadPool();
    private volatile boolean isRunning = true;

    public Worker( WorkQueue queue )
    {
        workQueue = queue;
    }


    public void start( ) throws WorkException
    {
        do
        {
            final DefaultWorkItem workItem = workQueue.getWork();
            if (workItem == null) 
            {
                isRunning = false;
                return;
            }
            threadPool.execute( new Runnable()
            {
                @Override
                public void run( )
                {
                    try
                    {
                        Work work = workItem.getResult();
                        workItem.setStatus( WorkEvent.WORK_STARTED);
                        work.run();
                        workItem.setStatus( WorkEvent.WORK_COMPLETED);
                    }
                    catch ( Throwable e )
                    {
                        workItem.setStatus( WorkEvent.WORK_REJECTED );
                    }
                }
            } );
        } while (isRunning);
    }
    
}
