2015-11-11 20:20:04 -08:00
|
|
|
// onjava/TaskManager.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// Managing and executing a queue of tasks.
|
2015-11-11 20:20:04 -08:00
|
|
|
package onjava;
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.concurrent.*;
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class TaskManager<R,C extends Callable<R>>
|
|
|
|
extends ArrayList<TaskItem<R,C>> {
|
|
|
|
private ExecutorService exec =
|
|
|
|
Executors.newSingleThreadExecutor();
|
|
|
|
public void add(C task) {
|
|
|
|
add(new TaskItem<>(exec.submit(task),task));
|
|
|
|
}
|
|
|
|
public List<R> getResults() {
|
|
|
|
Iterator<TaskItem<R,C>> items = iterator();
|
|
|
|
List<R> results = new ArrayList<>();
|
|
|
|
while(items.hasNext()) {
|
|
|
|
TaskItem<R,C> 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<String> purge() {
|
|
|
|
Iterator<TaskItem<R,C>> items = iterator();
|
|
|
|
List<String> results = new ArrayList<>();
|
|
|
|
while(items.hasNext()) {
|
|
|
|
TaskItem<R,C> 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;
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|