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