1 package org.robolectric.util;
2 
3 import java.util.concurrent.Callable;
4 import java.util.concurrent.CancellationException;
5 import java.util.concurrent.TimeUnit;
6 
7 /**
8  * A Future represents the result of an asynchronous computation.
9  *
10  * @param <T> The result type returned by this Future's get method.
11  * @deprecation This class can introduce deadlocks, since its lock is held while invoking run().
12  */
13 @Deprecated
14 public class SimpleFuture<T> {
15   private T result;
16   private boolean hasRun;
17   private boolean cancelled;
18   private final Callable<T> callable;
19 
SimpleFuture(Callable<T> callable)20   public SimpleFuture(Callable<T> callable) {
21     this.callable = callable;
22   }
23 
isCancelled()24   public boolean isCancelled() {
25     return cancelled;
26   }
27 
cancel(boolean mayInterruptIfRunning)28   public boolean cancel(boolean mayInterruptIfRunning) {
29     if (!hasRun) {
30       cancelled = true;
31       done();
32     }
33 
34     return cancelled;
35   }
36 
get()37   public synchronized T get() throws InterruptedException {
38     if (cancelled) {
39       throw new CancellationException();
40     } else {
41       while (!hasRun) this.wait();
42       return result;
43     }
44   }
45 
get(long timeout, TimeUnit unit)46   public synchronized T get(long timeout, TimeUnit unit) throws InterruptedException {
47     if (cancelled) {
48       throw new CancellationException();
49     } else {
50       while (!hasRun) this.wait(unit.toMillis(timeout));
51       return result;
52     }
53   }
54 
run()55   public synchronized void run() {
56     try {
57       if (!cancelled) {
58         result = callable.call();
59         hasRun = true;
60         done();
61       }
62     } catch (Exception e) {
63       throw new RuntimeException(e);
64     }
65 
66     this.notify();
67   }
68 
done()69   protected void done() {
70   }
71 }
72