I'm wondering what the best approach would be to handle multi threading in
a service so that I have other service classes available to me.

I'm passing in PDFService, but I'd like to pass it in through constructor
injection.

I'm assuming I'd have to instantiate the pool within archiveQueue and not
set a class variable followed by me binding WorkQueue to an interface? I

Current Code

public class WorkQueue {

    private final ExecutorService pool;

    private final PDFService pdfService;

    public WorkQueue(PDFService pdfService, int poolSize) {
        this.pdfService = pdfService;
        this.pool = Executors.newFixedThreadPool(poolSize);
    }

    public void archiveQueue(List<TimeSheet> timeSheets) {
        try {
            for (final TimeSheet timeSheet : timeSheets) {
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        pdfService.generatePDF(null, timeSheet);
                    }
                });
            }
        } catch (Exception ex) {
            Logger.getLogger(WorkQueue.class.getName()).log(Level.SEVERE,
null, ex);
        }
    }

    void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }

}

Reply via email to