File: FutureResult.java

package info (click to toggle)
concurrent-dfsg 1.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 976 kB
  • ctags: 2,018
  • sloc: java: 10,704; xml: 49; makefile: 12
file content (202 lines) | stat: -rw-r--r-- 5,910 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
  File: FutureResult.java

  Originally written by Doug Lea and released into the public domain.
  This may be used for any purposes whatsoever without acknowledgment.
  Thanks for the assistance and support of Sun Microsystems Labs,
  and everyone contributing, testing, and using this code.

  History:
  Date       Who                What
  30Jun1998  dl               Create public version
*/

package EDU.oswego.cs.dl.util.concurrent;
import java.lang.reflect.*;

/**
 * A  class maintaining a single reference variable serving as the result
 * of an operation. The result cannot be accessed until it has been set.
 * <p>
 * <b>Sample Usage</b> <p>
 * <pre>
 * class ImageRenderer { Image render(byte[] raw); }
 * class App {
 *   Executor executor = ...
 *   ImageRenderer renderer = ...
 *   void display(byte[] rawimage) {
 *     try {
 *       FutureResult futureImage = new FutureResult();
 *       Runnable command = futureImage.setter(new Callable() {
 *          public Object call() { return renderer.render(rawImage); }
 *       });
 *       executor.execute(command);
 *       drawBorders();             // do other things while executing
 *       drawCaption();
 *       drawImage((Image)(futureImage.get())); // use future
 *     }
 *     catch (InterruptedException ex) { return; }
 *     catch (InvocationTargetException ex) { cleanup(); return; }
 *   }
 * }
 * </pre>
 * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
 * @see Executor
 **/

public class FutureResult {
  /** The result of the operation **/
  protected Object value_ = null;
  
  /** Status -- true after first set **/
  protected boolean ready_ = false;

  /** the exception encountered by operation producing result **/
  protected InvocationTargetException exception_ = null;

  /** 
   * Create an initially unset FutureResult
   **/
  public FutureResult() { }


  /** 
   * Return a Runnable object that, when run, will set the result value.
   * @param function - a Callable object whose result will be
   * held by this FutureResult.
   * @return A Runnable object that, when run, will call the
   * function and (eventually) set the result.
   **/

  public Runnable setter(final Callable function) {
    return new Runnable() {
      public void run() {
        try {
          set(function.call());
        }
        catch(Throwable ex) {
          setException(ex);
        }
      }
    };
  }

  /** internal utility: either get the value or throw the exception **/
  protected Object doGet() throws InvocationTargetException {
    if (exception_ != null) 
      throw exception_;
    else
      return value_; 
  }

  /**
   * Access the reference, waiting if necessary until it is ready.
   * @return current value
   * @exception InterruptedException if current thread has been interrupted
   * @exception InvocationTargetException if the operation
   * producing the value encountered an exception.
   **/
  public synchronized Object get() 
    throws InterruptedException, InvocationTargetException {
    while (!ready_) wait();
    return doGet();
  }



  /**
   * Wait at most msecs to access the reference.
   * @return current value
   * @exception TimeoutException if not ready after msecs
   * @exception InterruptedException if current thread has been interrupted
   * @exception InvocationTargetException if the operation
   * producing the value encountered an exception.
   **/
  public synchronized Object timedGet(long msecs) 
    throws TimeoutException, InterruptedException, InvocationTargetException {
    long startTime = (msecs <= 0)? 0 : System.currentTimeMillis();
    long waitTime = msecs;
    if (ready_) return doGet();
    else if (waitTime <= 0) throw new TimeoutException(msecs);
    else {
      for (;;) {
        wait(waitTime);
        if (ready_) return doGet();
        else {
          waitTime = msecs - (System.currentTimeMillis() - startTime);
          if (waitTime <= 0)
            throw new TimeoutException(msecs);
        }
      }
    }
  }

  /**
   * Set the reference, and signal that it is ready. It is not
   * considered an error to set the value more than once,
   * but it is not something you would normally want to do.
   * @param newValue The value that will be returned by a subsequent get();
   **/
  public synchronized void set(Object newValue) {
    value_ = newValue;
    ready_ = true;
    notifyAll();
  }

  /**
   * Set the exception field, also setting ready status.
   * @param ex The exception. It will be reported out wrapped
   * within an InvocationTargetException 
   **/
  public synchronized void setException(Throwable ex) {
    exception_ = new InvocationTargetException(ex);
    ready_ = true;
    notifyAll();
  }


  /**
   * Get the exception, or null if there isn't one (yet).
   * This does not wait until the future is ready, so should
   * ordinarily only be called if you know it is.
   * @return the exception encountered by the operation
   * setting the future, wrapped in an InvocationTargetException
   **/
  public synchronized InvocationTargetException getException() {
    return exception_;
  }

  /**
   * Return whether the reference or exception have been set.
   * @return true if has been set. else false
   **/
  public synchronized boolean isReady() {
    return ready_; 
  }

  /**
   * Access the reference, even if not ready
   * @return current value
   **/
  public synchronized Object peek() {
    return value_; 
  }


  /**
   * Clear the value and exception and set to not-ready,
   * allowing this FutureResult to be reused. This is not
   * particularly recommended and must be done only
   * when you know that no other object is depending on the
   * properties of this FutureResult.
   **/
  public synchronized void clear() {
    value_ = null;
    exception_ = null;
    ready_ = false;
  }

}