OSDN Git Service

完了、キャンセル、エラーを通知するインタフェース追加
[coroid/inqubus.git] / frontend / src / saccubus / worker / Worker.java
1 package saccubus.worker;
2
3 import java.util.concurrent.Callable;
4
5 /**
6  * 途中経過を報告できるCallableです.
7  *
8  * @author yuki
9  */
10 public abstract class Worker<T, V> implements Callable<T> {
11
12     private static int serialNumber = 0;
13     private final int id;
14     private final WorkerListener<T, V> listener;
15
16     public Worker(WorkerListener<T, V> listener) {
17         this.id = ++serialNumber;
18         this.listener = listener;
19     }
20
21     @Override
22     public final T call() throws Exception {
23         try {
24             final T result = doInBackground();
25             if (listener != null) {
26                 listener.done(result);
27             }
28             return result;
29         } catch (InterruptedException ex) {
30             if( listener != null){
31                 listener.cancelled();
32             }
33             throw ex;
34         } catch (Throwable th) {
35             if(listener != null){
36                 listener.error(th);
37             }
38             throw th;
39         }
40     }
41
42     protected abstract T doInBackground() throws Exception;
43
44     public final int getId() {
45         return id;
46     }
47
48     protected final void publish(V value) {
49         if (listener != null) {
50             listener.process(value);
51         }
52     }
53 }