// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class ErSoQueueDQImpl implements ErSoQueue {
    private static class Token {
    }
    private static class InterruptedResult extends Result {
        public InterruptedResult() {
            super(false);
        }
    }
    private static class ErSoExceptionNothing extends ErSoException {
        private static final long serialVersionUID = 1L;
        public ErSoExceptionNothing() {
            super("Nothing to wait for");
        }
    }
    private ExecutorService es;
    private BlockingQueue<Result> results;
    private ConcurrentLinkedQueue<Token> tokens;
    public ErSoQueueDQImpl(int noworkers, int maxpending) {
        es = Executors.newFixedThreadPool(noworkers);
        results = new LinkedBlockingQueue<Result>(maxpending);
        tokens = new ConcurrentLinkedQueue<Token>();
    }
    @Override
    public void submitWork(final Work w) {
        tokens.add(new Token());
        es.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    results.put(w.call());
                } catch (InterruptedException e) {
                    // this is expected in case of stop(false)
                    try {
                        results.put(new InterruptedResult());
                    } catch (InterruptedException e2) {
                        // not sure what can be done here
                        e2.printStackTrace();
                    }
                } catch (Exception e) {
                    // not specified what action should be done here
                    e.printStackTrace();
                }
            }
        });
    }
    @Override
    public Result getResult() throws ErSoException {
        try {
            if(tokens.poll() != null) {
                return results.take();
            } else {
                throw new ErSoExceptionNothing();
            }
        } catch (InterruptedException e) {
            throw new ErSoException(e);
        }
    }
    @Override
    public void stop(boolean wait) {
        if(wait) {
            es.shutdown();
        } else {
            for(@SuppressWarnings("unused") Runnable r : es.shutdownNow()) {
                try {
                    results.put(new InterruptedResult());
                } catch (InterruptedException e) {
                    // not sure what can be done here
                    e.printStackTrace();
                }
            }
        }
    }
}
