]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.graphviz/src/org/simantics/graphviz/continuation/Computation.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.graphviz / src / org / simantics / graphviz / continuation / Computation.java
1 package org.simantics.graphviz.continuation;
2
3 import java.util.ArrayList;
4 import java.util.concurrent.CancellationException;
5 import java.util.concurrent.CountDownLatch;
6
7 public abstract class Computation<T> {
8     T result;
9     Exception exception;
10     ArrayList<Continuation<T>> continuations = new ArrayList<Continuation<T>>(); 
11     CountDownLatch doneGate = new CountDownLatch(1); 
12
13     public void addContinuation(Continuation<T> continuation) {
14         synchronized(doneGate) {
15             if(doneGate.getCount() == 0) {
16                 if(exception == null)
17                     continuation.succeeded(result);
18                 else
19                     continuation.failed(exception);
20             }
21             else
22                 continuations.add(continuation);
23         }
24     }
25
26     public boolean isDone() {
27         return doneGate.getCount() == 0;
28     }
29     
30     protected void failWith(Exception exception) {
31         this.exception = exception;
32         ArrayList<Continuation<T>> cs;
33         synchronized (doneGate) {
34             cs = this.continuations;
35             this.continuations = null;
36             doneGate.countDown();
37         }
38         if(cs != null)
39             for(Continuation<T> continuation : cs)
40                 continuation.failed(exception);
41     }
42     
43     protected void doneWith(T result) {
44         this.result = result;
45         ArrayList<Continuation<T>> cs;
46         synchronized (doneGate) {
47             cs = this.continuations;
48             this.continuations = null;
49             doneGate.countDown();
50         }
51         if(cs != null)
52             for(Continuation<T> continuation : cs)
53                 continuation.succeeded(result);
54     }
55     
56     public void cancel() {
57         failWith(new CancellationException());
58     }
59     
60     public T get() throws Exception {
61         doneGate.await();
62         if(exception != null)
63             throw exception;
64         return result;
65     }
66 }