// onjava/TaskManager.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Managing and executing a queue of tasks. package onjava; import java.util.concurrent.*; import java.util.*; public class TaskManager> extends ArrayList> { private ExecutorService exec = Executors.newSingleThreadExecutor(); public void add(C task) { add(new TaskItem<>(exec.submit(task),task)); } public List getResults() { Iterator> items = iterator(); List results = new ArrayList<>(); while(items.hasNext()) { TaskItem item = items.next(); if(item.future.isDone()) { try { results.add(item.future.get()); } catch(InterruptedException | ExecutionException e) { throw new RuntimeException(e); } items.remove(); } } return results; } public List purge() { Iterator> items = iterator(); List results = new ArrayList<>(); while(items.hasNext()) { TaskItem item = items.next(); // Leave completed tasks for results reporting: if(!item.future.isDone()) { results.add("Cancelling " + item.task); item.future.cancel(true); // Can interrupt items.remove(); } } return results; } }