ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Future.java
Revision: 1.45
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.44: +139 -0 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.12 * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.22 * Expert Group and released to the public domain, as explained at
4 jsr166 1.35 * http://creativecommons.org/publicdomain/zero/1.0/
5 tim 1.1 */
6    
7     package java.util.concurrent;
8    
9     /**
10 jsr166 1.37 * A {@code Future} represents the result of an asynchronous
11 dl 1.12 * 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 jsr166 1.37 * {@code get} when the computation has completed, blocking if
15 dl 1.17 * necessary until it is ready. Cancellation is performed by the
16 jsr166 1.37 * {@code cancel} method. Additional methods are provided to
17 dl 1.17 * determine if the task completed normally or was cancelled. Once a
18     * computation has completed, the computation cannot be cancelled.
19 jsr166 1.37 * If you would like to use a {@code Future} for the sake
20 dl 1.21 * of cancellability but not provide a usable result, you can
21 jsr166 1.34 * declare types of the form {@code Future<?>} and
22 jsr166 1.37 * return {@code null} as a result of the underlying task.
23 tim 1.1 *
24 jsr166 1.41 * <p><b>Sample Usage</b> (Note that the following classes are all
25 jsr166 1.38 * made-up.)
26     *
27 jsr166 1.40 * <pre> {@code
28 dl 1.10 * interface ArchiveSearcher { String search(String target); }
29 tim 1.1 * class App {
30 dl 1.43 * ExecutorService executor = ...;
31     * ArchiveSearcher searcher = ...;
32 jsr166 1.41 * void showSearch(String target) throws InterruptedException {
33     * Callable<String> task = () -> searcher.search(target);
34     * Future<String> future = executor.submit(task);
35 dl 1.5 * displayOtherThings(); // do other things while searching
36 tim 1.1 * try {
37 dl 1.5 * displayText(future.get()); // use future
38 tim 1.8 * } catch (ExecutionException ex) { cleanup(); return; }
39 tim 1.1 * }
40 jsr166 1.34 * }}</pre>
41 tim 1.1 *
42 jsr166 1.37 * 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 jsr166 1.40 * <pre> {@code
46 jsr166 1.41 * FutureTask<String> future = new FutureTask<>(task);
47 jsr166 1.36 * executor.execute(future);}</pre>
48 brian 1.29 *
49 jsr166 1.31 * <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 dl 1.30 *
53 tim 1.1 * @see FutureTask
54     * @see Executor
55 dl 1.12 * @since 1.5
56 dl 1.4 * @author Doug Lea
57 jsr166 1.37 * @param <V> The result type returned by this Future's {@code get} method
58 tim 1.1 */
59 dl 1.17 public interface Future<V> {
60    
61     /**
62 dl 1.42 * 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 dl 1.44 *
75 dl 1.42 * @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 jsr166 1.37 * @return {@code false} if the task could not be cancelled,
80 dl 1.42 * 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 dl 1.17 */
85     boolean cancel(boolean mayInterruptIfRunning);
86    
87     /**
88 jsr166 1.37 * Returns {@code true} if this task was cancelled before it completed
89 dl 1.17 * normally.
90     *
91 jsr166 1.37 * @return {@code true} if this task was cancelled before it completed
92 dl 1.17 */
93     boolean isCancelled();
94    
95     /**
96 jsr166 1.37 * Returns {@code true} if this task completed.
97 dl 1.17 *
98     * Completion may be due to normal termination, an exception, or
99     * cancellation -- in all of these cases, this method will return
100 jsr166 1.37 * {@code true}.
101 jsr166 1.24 *
102 jsr166 1.37 * @return {@code true} if this task completed
103 dl 1.17 */
104     boolean isDone();
105 tim 1.1
106     /**
107 dl 1.23 * Waits if necessary for the computation to complete, and then
108 tim 1.1 * retrieves its result.
109     *
110 dl 1.23 * @return the computed result
111     * @throws CancellationException if the computation was cancelled
112     * @throws ExecutionException if the computation threw an
113 dl 1.4 * exception
114 dl 1.23 * @throws InterruptedException if the current thread was interrupted
115 dl 1.4 * while waiting
116 tim 1.1 */
117     V get() throws InterruptedException, ExecutionException;
118    
119     /**
120     * Waits if necessary for at most the given time for the computation
121 dl 1.23 * to complete, and then retrieves its result, if available.
122 tim 1.1 *
123     * @param timeout the maximum time to wait
124 dl 1.14 * @param unit the time unit of the timeout argument
125 dl 1.23 * @return the computed result
126     * @throws CancellationException if the computation was cancelled
127     * @throws ExecutionException if the computation threw an
128 dl 1.4 * exception
129 dl 1.23 * @throws InterruptedException if the current thread was interrupted
130 dl 1.4 * while waiting
131 tim 1.1 * @throws TimeoutException if the wait timed out
132     */
133 dl 1.14 V get(long timeout, TimeUnit unit)
134 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException;
135 dl 1.45
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 a filter-map of a stream of
141     * Future objects where the filter matches tasks that completed successfully.
142     * {@snippet lang=java :
143     * results = futures.stream()
144     * .filter(f -> f.state() == Future.State.SUCCESS)
145     * .map(Future::resultNow)
146     * .toList();
147     * }
148     *
149     * @implSpec
150     * The default implementation invokes {@code isDone()} to test if the task
151     * has completed. If done, it invokes {@code get()} to obtain the result.
152     *
153     * @return the computed result
154     * @throws IllegalStateException if the task has not completed or the task
155     * did not complete with a result
156     * @since 99
157     */
158     default V resultNow() {
159     if (!isDone())
160     throw new IllegalStateException("Task has not completed");
161     boolean interrupted = false;
162     try {
163     while (true) {
164     try {
165     return get();
166     } catch (InterruptedException e) {
167     interrupted = true;
168     } catch (ExecutionException e) {
169     throw new IllegalStateException("Task completed with exception");
170     } catch (CancellationException e) {
171     throw new IllegalStateException("Task was cancelled");
172     }
173     }
174     } finally {
175     if (interrupted) Thread.currentThread().interrupt();
176     }
177     }
178    
179     /**
180     * Returns the exception thrown by the task, without waiting.
181     *
182     * <p> This method is for cases where the caller knows that the task
183     * has already completed with an exception.
184     *
185     * @implSpec
186     * The default implementation invokes {@code isDone()} to test if the task
187     * has completed. If done and not cancelled, it invokes {@code get()} and
188     * catches the {@code ExecutionException} to obtain the exception.
189     *
190     * @return the exception thrown by the task
191     * @throws IllegalStateException if the task has not completed, the task
192     * completed normally, or the task was cancelled
193     * @since 99
194     */
195     default Throwable exceptionNow() {
196     if (!isDone())
197     throw new IllegalStateException("Task has not completed");
198     if (isCancelled())
199     throw new IllegalStateException("Task was cancelled");
200     boolean interrupted = false;
201     try {
202     while (true) {
203     try {
204     get();
205     throw new IllegalStateException("Task completed with a result");
206     } catch (InterruptedException e) {
207     interrupted = true;
208     } catch (ExecutionException e) {
209     return e.getCause();
210     }
211     }
212     } finally {
213     if (interrupted) Thread.currentThread().interrupt();
214     }
215     }
216    
217     /**
218     * Represents the computation state.
219     * @since 99
220     */
221     enum State {
222     /**
223     * The task has not completed.
224     */
225     RUNNING,
226     /**
227     * The task completed with a result.
228     * @see Future#resultNow()
229     */
230     SUCCESS,
231     /**
232     * The task completed with an exception.
233     * @see Future#exceptionNow()
234     */
235     FAILED,
236     /**
237     * The task was cancelled.
238     * @see #cancel(boolean)
239     */
240     CANCELLED
241     }
242    
243     /**
244     * {@return the computation state}
245     *
246     * @implSpec
247     * The default implementation uses {@code isDone()}, {@code isCancelled()},
248     * and {@code get()} to determine the state.
249     *
250     * @since 99
251     */
252     default State state() {
253     if (!isDone())
254     return State.RUNNING;
255     if (isCancelled())
256     return State.CANCELLED;
257     boolean interrupted = false;
258     try {
259     while (true) {
260     try {
261     get(); // may throw InterruptedException when done
262     return State.SUCCESS;
263     } catch (InterruptedException e) {
264     interrupted = true;
265     } catch (ExecutionException e) {
266     return State.FAILED;
267     }
268     }
269     } finally {
270     if (interrupted) Thread.currentThread().interrupt();
271     }
272     }
273 tim 1.1 }
274 dl 1.45