1 package org.simantics.graphviz.continuation;
3 import java.util.ArrayList;
4 import java.util.concurrent.CancellationException;
5 import java.util.concurrent.CountDownLatch;
7 public abstract class Computation<T> {
10 ArrayList<Continuation<T>> continuations = new ArrayList<Continuation<T>>();
11 CountDownLatch doneGate = new CountDownLatch(1);
13 public void addContinuation(Continuation<T> continuation) {
14 synchronized(doneGate) {
15 if(doneGate.getCount() == 0) {
17 continuation.succeeded(result);
19 continuation.failed(exception);
22 continuations.add(continuation);
26 public boolean isDone() {
27 return doneGate.getCount() == 0;
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;
39 for(Continuation<T> continuation : cs)
40 continuation.failed(exception);
43 protected void doneWith(T result) {
45 ArrayList<Continuation<T>> cs;
46 synchronized (doneGate) {
47 cs = this.continuations;
48 this.continuations = null;
52 for(Continuation<T> continuation : cs)
53 continuation.succeeded(result);
56 public void cancel() {
57 failWith(new CancellationException());
60 public T get() throws Exception {