|
1 |
| package edu.rice.cs.plt.concurrent; |
|
2 |
| |
|
3 |
| import java.util.concurrent.Executor; |
|
4 |
| |
|
5 |
| import edu.rice.cs.plt.lambda.WrappedException; |
|
6 |
| |
|
7 |
| |
|
8 |
| |
|
9 |
| |
|
10 |
| |
|
11 |
| |
|
12 |
| |
|
13 |
| |
|
14 |
| |
|
15 |
| public class ExecutorIncrementalTaskController<I, R> extends IncrementalTaskController<I, R> { |
|
16 |
| |
|
17 |
| private Executor _executor; |
|
18 |
| private IncrementalTask<? extends I, ? extends R> _task; |
|
19 |
| private CompletionMonitor _continueMonitor; |
|
20 |
| |
|
21 |
| private volatile Thread _t; |
|
22 |
| |
|
23 |
1
| public ExecutorIncrementalTaskController(Executor executor, IncrementalTask<? extends I, ? extends R> task,
|
|
24 |
| boolean ignoreIntermediate) { |
|
25 |
1
| super(ignoreIntermediate);
|
|
26 |
1
| _executor = executor;
|
|
27 |
1
| _task = task;
|
|
28 |
1
| _continueMonitor = new CompletionMonitor(false);
|
|
29 |
1
| _t = null;
|
|
30 |
| } |
|
31 |
| |
|
32 |
1
| protected void doStart() {
|
|
33 |
1
| _continueMonitor.signal();
|
|
34 |
1
| _executor.execute(new Runnable() {
|
|
35 |
1
| public void run() {
|
|
36 |
1
| _t = Thread.currentThread();
|
|
37 |
1
| started();
|
|
38 |
1
| try {
|
|
39 |
1
| while (!_task.isResolved()) {
|
|
40 |
5
| authorizeContinue();
|
|
41 |
5
| stepped(_task.step());
|
|
42 |
| } |
|
43 |
1
| authorizeContinue();
|
|
44 |
1
| finishedCleanly(_task.value());
|
|
45 |
| } |
|
46 |
| catch (WrappedException e) { |
|
47 |
0
| if (e.getCause() instanceof InterruptedException) { stopped(); }
|
|
48 |
0
| else { finishedWithTaskException(e); }
|
|
49 |
| } |
|
50 |
0
| catch (RuntimeException e) { finishedWithTaskException(e); }
|
|
51 |
0
| catch (InterruptedException e) { stopped(); }
|
|
52 |
0
| catch (Throwable t) { finishedWithImplementationException(new WrappedException(t)); }
|
|
53 |
| } |
|
54 |
6
| private void authorizeContinue() throws InterruptedException {
|
|
55 |
0
| if (Thread.interrupted()) { throw new InterruptedException(); }
|
|
56 |
6
| if (!_continueMonitor.isSignaled()) {
|
|
57 |
1
| paused();
|
|
58 |
1
| _continueMonitor.ensureSignaled();
|
|
59 |
1
| started();
|
|
60 |
| } |
|
61 |
| } |
|
62 |
| }); |
|
63 |
| } |
|
64 |
| |
|
65 |
1
| protected void doPause() { _continueMonitor.reset(); }
|
|
66 |
1
| protected void doResume() { _continueMonitor.signal(); }
|
|
67 |
0
| protected void doStop() { _t.interrupt(); }
|
|
68 |
1
| protected void discard() { _executor = null; _task = null; _continueMonitor = null; _t = null; }
|
|
69 |
| |
|
70 |
| } |