01: package snow.concurrent;
02:
03: import tide.editor.MainEditorFrame;
04: import java.util.concurrent.*;
05: import java.util.*;
06:
07: /** An easy task manager fifo single threaded queue.
08: */
09: public class TaskManager {
10: // only one task at time, one after each other
11: final private ExecutorService executor = Executors
12: .newFixedThreadPool(1);
13: final private List<InterruptableTask> submitedTasks = new ArrayList<InterruptableTask>(); // all the tasks maybe actual, past and futures
14:
15: public TaskManager() {
16: }
17:
18: public <T> Future<T> execute(InterruptableTask<T> task) {
19: Future<T> fut = executor.submit((Callable<T>) task); // Callable
20: task.future = fut;
21: synchronized (submitedTasks) {
22: submitedTasks.add(task);
23: }
24: cleanDoneTasks();
25: return fut;
26: }
27:
28: /** Cancel all running tasks.
29: */
30: public void deleteWaitingTasks() {
31: synchronized (submitedTasks) {
32: for (int i = submitedTasks.size() - 1; i >= 0; i--) {
33: InterruptableTask it = submitedTasks.get(i);
34: it.future.cancel(true);
35: }
36: }
37: cleanDoneTasks();
38: }
39:
40: public void stopActualTask(long timeout) {
41: synchronized (submitedTasks) {
42: if (submitedTasks.isEmpty())
43: return;
44:
45: cleanDoneTasks();
46: InterruptableTask at = getActualExecutedTask();
47: if (at != null) {
48: if (at.interrupter.getShouldStopEvaluation()) {
49: MainEditorFrame.debugOut("kill task");
50: at.kill();
51: } else {
52: MainEditorFrame.debugOut("Request stop");
53: at.requestStop();
54: }
55: }
56: }
57: }
58:
59: private void cleanDoneTasks() {
60: synchronized (submitedTasks) {
61: for (int i = submitedTasks.size() - 1; i >= 0; i--) {
62: if (submitedTasks.get(i).future.isDone()) {
63: submitedTasks.remove(i);
64: }
65: }
66: }
67: }
68:
69: public InterruptableTask getActualExecutedTask() {
70: synchronized (submitedTasks) {
71: for (int i = 0; i < submitedTasks.size(); i++) {
72: if (submitedTasks.get(i).isExecuting()) {
73: return submitedTasks.get(i);
74: }
75: }
76: }
77: return null;
78: }
79:
80: }
|