1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
/** |
10 |
* A {@code Future} represents the result of an asynchronous |
11 |
* computation. Methods are provided to check if the computation is |
12 |
* complete, to wait for its completion, and to retrieve the result of |
13 |
* the computation. The result can only be retrieved using method |
14 |
* {@code get} when the computation has completed, blocking if |
15 |
* necessary until it is ready. Cancellation is performed by the |
16 |
* {@code cancel} method. Additional methods are provided to |
17 |
* determine if the task completed normally or was cancelled. Once a |
18 |
* computation has completed, the computation cannot be cancelled. |
19 |
* If you would like to use a {@code Future} for the sake |
20 |
* of cancellability but not provide a usable result, you can |
21 |
* declare types of the form {@code Future<?>} and |
22 |
* return {@code null} as a result of the underlying task. |
23 |
* |
24 |
* <p><b>Sample Usage</b> (Note that the following classes are all |
25 |
* made-up.) |
26 |
* |
27 |
* <pre> {@code |
28 |
* interface ArchiveSearcher { String search(String target); } |
29 |
* class App { |
30 |
* ExecutorService executor = ...; |
31 |
* ArchiveSearcher searcher = ...; |
32 |
* void showSearch(String target) throws InterruptedException { |
33 |
* Callable<String> task = () -> searcher.search(target); |
34 |
* Future<String> future = executor.submit(task); |
35 |
* displayOtherThings(); // do other things while searching |
36 |
* try { |
37 |
* displayText(future.get()); // use future |
38 |
* } catch (ExecutionException ex) { cleanup(); return; } |
39 |
* } |
40 |
* }}</pre> |
41 |
* |
42 |
* The {@link FutureTask} class is an implementation of {@code Future} that |
43 |
* implements {@code Runnable}, and so may be executed by an {@code Executor}. |
44 |
* For example, the above construction with {@code submit} could be replaced by: |
45 |
* <pre> {@code |
46 |
* FutureTask<String> future = new FutureTask<>(task); |
47 |
* executor.execute(future);}</pre> |
48 |
* |
49 |
* <p>Memory consistency effects: Actions taken by the asynchronous computation |
50 |
* <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a> |
51 |
* actions following the corresponding {@code Future.get()} in another thread. |
52 |
* |
53 |
* @see FutureTask |
54 |
* @see Executor |
55 |
* @since 1.5 |
56 |
* @author Doug Lea |
57 |
* @param <V> The result type returned by this Future's {@code get} method |
58 |
*/ |
59 |
public interface Future<V> { |
60 |
|
61 |
/** |
62 |
* Attempts to cancel execution of this task. This method has no |
63 |
* effect if the task is already completed or cancelled, or could |
64 |
* not be cancelled for some other reason. Otherwise, if this |
65 |
* task has not started when {@code cancel} is called, this task |
66 |
* should never run. If the task has already started, then the |
67 |
* {@code mayInterruptIfRunning} parameter determines whether the |
68 |
* thread executing this task (when known by the implementation) |
69 |
* is interrupted in an attempt to stop the task. |
70 |
* |
71 |
* <p>The return value from this method does not necessarily |
72 |
* indicate whether the task is now cancelled; use {@link |
73 |
* #isCancelled}. |
74 |
* |
75 |
* @param mayInterruptIfRunning {@code true} if the thread |
76 |
* executing this task should be interrupted (if the thread is |
77 |
* known to the implementation); otherwise, in-progress tasks are |
78 |
* allowed to complete |
79 |
* @return {@code false} if the task could not be cancelled, |
80 |
* typically because it has already completed; {@code true} |
81 |
* otherwise. If two or more threads cause a task to be cancelled, |
82 |
* then at least one of them returns {@code true}. Implementations |
83 |
* may provide stronger guarantees. |
84 |
*/ |
85 |
boolean cancel(boolean mayInterruptIfRunning); |
86 |
|
87 |
/** |
88 |
* Returns {@code true} if this task was cancelled before it completed |
89 |
* normally. |
90 |
* |
91 |
* @return {@code true} if this task was cancelled before it completed |
92 |
*/ |
93 |
boolean isCancelled(); |
94 |
|
95 |
/** |
96 |
* Returns {@code true} if this task completed. |
97 |
* |
98 |
* Completion may be due to normal termination, an exception, or |
99 |
* cancellation -- in all of these cases, this method will return |
100 |
* {@code true}. |
101 |
* |
102 |
* @return {@code true} if this task completed |
103 |
*/ |
104 |
boolean isDone(); |
105 |
|
106 |
/** |
107 |
* Waits if necessary for the computation to complete, and then |
108 |
* retrieves its result. |
109 |
* |
110 |
* @return the computed result |
111 |
* @throws CancellationException if the computation was cancelled |
112 |
* @throws ExecutionException if the computation threw an |
113 |
* exception |
114 |
* @throws InterruptedException if the current thread was interrupted |
115 |
* while waiting |
116 |
*/ |
117 |
V get() throws InterruptedException, ExecutionException; |
118 |
|
119 |
/** |
120 |
* Waits if necessary for at most the given time for the computation |
121 |
* to complete, and then retrieves its result, if available. |
122 |
* |
123 |
* @param timeout the maximum time to wait |
124 |
* @param unit the time unit of the timeout argument |
125 |
* @return the computed result |
126 |
* @throws CancellationException if the computation was cancelled |
127 |
* @throws ExecutionException if the computation threw an |
128 |
* exception |
129 |
* @throws InterruptedException if the current thread was interrupted |
130 |
* while waiting |
131 |
* @throws TimeoutException if the wait timed out |
132 |
*/ |
133 |
V get(long timeout, TimeUnit unit) |
134 |
throws InterruptedException, ExecutionException, TimeoutException; |
135 |
|
136 |
/** |
137 |
* Returns the computed result, without waiting. |
138 |
* |
139 |
* <p>This method is for cases where the caller knows that the task has |
140 |
* already completed successfully, for example when filtering a stream |
141 |
* of Future objects for the successful tasks and using a mapping |
142 |
* operation to obtain a stream of results. |
143 |
* {@snippet lang=java : |
144 |
* results = futures.stream() |
145 |
* .filter(f -> f.state() == Future.State.SUCCESS) |
146 |
* .map(Future::resultNow) |
147 |
* .toList(); |
148 |
* } |
149 |
* |
150 |
* @implSpec |
151 |
* The default implementation invokes {@code isDone()} to test if the task |
152 |
* has completed. If done, it invokes {@code get()} to obtain the result. |
153 |
* |
154 |
* @return the computed result |
155 |
* @throws IllegalStateException if the task has not completed or the task |
156 |
* did not complete with a result |
157 |
* @since 19 |
158 |
*/ |
159 |
default V resultNow() { |
160 |
if (!isDone()) |
161 |
throw new IllegalStateException("Task has not completed"); |
162 |
boolean interrupted = false; |
163 |
try { |
164 |
while (true) { |
165 |
try { |
166 |
return get(); |
167 |
} catch (InterruptedException e) { |
168 |
interrupted = true; |
169 |
} catch (ExecutionException e) { |
170 |
throw new IllegalStateException("Task completed with exception"); |
171 |
} catch (CancellationException e) { |
172 |
throw new IllegalStateException("Task was cancelled"); |
173 |
} |
174 |
} |
175 |
} finally { |
176 |
if (interrupted) Thread.currentThread().interrupt(); |
177 |
} |
178 |
} |
179 |
|
180 |
/** |
181 |
* Returns the exception thrown by the task, without waiting. |
182 |
* |
183 |
* <p>This method is for cases where the caller knows that the task |
184 |
* has already completed with an exception. |
185 |
* |
186 |
* @implSpec |
187 |
* The default implementation invokes {@code isDone()} to test if the task |
188 |
* has completed. If done and not cancelled, it invokes {@code get()} and |
189 |
* catches the {@code ExecutionException} to obtain the exception. |
190 |
* |
191 |
* @return the exception thrown by the task |
192 |
* @throws IllegalStateException if the task has not completed, the task |
193 |
* completed normally, or the task was cancelled |
194 |
* @since 19 |
195 |
*/ |
196 |
default Throwable exceptionNow() { |
197 |
if (!isDone()) |
198 |
throw new IllegalStateException("Task has not completed"); |
199 |
if (isCancelled()) |
200 |
throw new IllegalStateException("Task was cancelled"); |
201 |
boolean interrupted = false; |
202 |
try { |
203 |
while (true) { |
204 |
try { |
205 |
get(); |
206 |
throw new IllegalStateException("Task completed with a result"); |
207 |
} catch (InterruptedException e) { |
208 |
interrupted = true; |
209 |
} catch (ExecutionException e) { |
210 |
return e.getCause(); |
211 |
} |
212 |
} |
213 |
} finally { |
214 |
if (interrupted) Thread.currentThread().interrupt(); |
215 |
} |
216 |
} |
217 |
|
218 |
/** |
219 |
* Represents the computation state. |
220 |
* @since 19 |
221 |
*/ |
222 |
enum State { |
223 |
/** |
224 |
* The task has not completed. |
225 |
*/ |
226 |
RUNNING, |
227 |
/** |
228 |
* The task completed with a result. |
229 |
* @see Future#resultNow() |
230 |
*/ |
231 |
SUCCESS, |
232 |
/** |
233 |
* The task completed with an exception. |
234 |
* @see Future#exceptionNow() |
235 |
*/ |
236 |
FAILED, |
237 |
/** |
238 |
* The task was cancelled. |
239 |
* @see #cancel(boolean) |
240 |
*/ |
241 |
CANCELLED |
242 |
} |
243 |
|
244 |
/** |
245 |
* {@return the computation state} |
246 |
* |
247 |
* @implSpec |
248 |
* The default implementation uses {@code isDone()}, {@code isCancelled()}, |
249 |
* and {@code get()} to determine the state. |
250 |
* |
251 |
* @since 19 |
252 |
*/ |
253 |
default State state() { |
254 |
if (!isDone()) |
255 |
return State.RUNNING; |
256 |
if (isCancelled()) |
257 |
return State.CANCELLED; |
258 |
boolean interrupted = false; |
259 |
try { |
260 |
while (true) { |
261 |
try { |
262 |
get(); // may throw InterruptedException when done |
263 |
return State.SUCCESS; |
264 |
} catch (InterruptedException e) { |
265 |
interrupted = true; |
266 |
} catch (ExecutionException e) { |
267 |
return State.FAILED; |
268 |
} |
269 |
} |
270 |
} finally { |
271 |
if (interrupted) Thread.currentThread().interrupt(); |
272 |
} |
273 |
} |
274 |
} |