1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.student.common.ui.client.mvc;
17
18
19
20
21 import java.util.LinkedList;
22
23 public class WorkQueue {
24 public static abstract class WorkItem {
25 private boolean canceled = false;
26
27 public abstract void exec(final Callback<Boolean> onCompleteCallback);
28
29 public boolean isCanceled() {
30 return this.canceled;
31 }
32
33 protected void setCanceled(final boolean canceled) {
34 this.canceled = canceled;
35 }
36 }
37
38 private boolean running = false;
39 private final LinkedList<WorkItem> queue = new LinkedList<WorkItem>();
40
41 private final Callback<Boolean> onCompleteCallback = new Callback<Boolean>() {
42 @Override
43 public void exec(final Boolean value) {
44 processNext();
45 }
46 };
47
48 public void clear() {
49 for (final WorkItem item : queue) {
50 item.setCanceled(true);
51 }
52 queue.clear();
53 }
54
55 public boolean isRunning() {
56 return this.running;
57 }
58
59 private void processNext() {
60 WorkItem item = null;
61 while (!queue.isEmpty() && (item = queue.removeFirst()) != null) {
62 if (item.isCanceled()) {
63 item = null;
64 } else {
65 break;
66 }
67 }
68 if (item == null) {
69 running = false;
70 } else {
71 item.exec(onCompleteCallback);
72 }
73 }
74
75 public void submit(final WorkItem item) {
76 queue.add(item);
77 if (!running) {
78 running = true;
79 processNext();
80 }
81 }
82 }