ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorCompletionService.java
Revision: 1.30
Committed: Sun Sep 3 15:57:23 2017 UTC (6 years, 8 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.29: +8 -0 lines
Log Message:
use @inheritDoc for unchecked exceptions

File Contents

# Content
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 {@link CompletionService} that uses a supplied {@link Executor}
11 * to execute tasks. This class arranges that submitted tasks are,
12 * upon completion, placed on a queue accessible using {@code take}.
13 * The class is lightweight enough to be suitable for transient use
14 * when processing groups of tasks.
15 *
16 * <p>
17 *
18 * <b>Usage Examples.</b>
19 *
20 * Suppose you have a set of solvers for a certain problem, each
21 * returning a value of some type {@code Result}, and would like to
22 * run them concurrently, processing the results of each of them that
23 * return a non-null value, in some method {@code use(Result r)}. You
24 * could write this as:
25 *
26 * <pre> {@code
27 * void solve(Executor e,
28 * Collection<Callable<Result>> solvers)
29 * throws InterruptedException, ExecutionException {
30 * CompletionService<Result> cs
31 * = new ExecutorCompletionService<>(e);
32 * solvers.forEach(cs::submit);
33 * for (int i = solvers.size(); i > 0; i--) {
34 * Result r = cs.take().get();
35 * if (r != null)
36 * use(r);
37 * }
38 * }}</pre>
39 *
40 * Suppose instead that you would like to use the first non-null result
41 * of the set of tasks, ignoring any that encounter exceptions,
42 * and cancelling all other tasks when the first one is ready:
43 *
44 * <pre> {@code
45 * void solve(Executor e,
46 * Collection<Callable<Result>> solvers)
47 * throws InterruptedException {
48 * CompletionService<Result> cs
49 * = new ExecutorCompletionService<>(e);
50 * int n = solvers.size();
51 * List<Future<Result>> futures = new ArrayList<>(n);
52 * Result result = null;
53 * try {
54 * solvers.forEach(solver -> futures.add(cs.submit(solver)));
55 * for (int i = n; i > 0; i--) {
56 * try {
57 * Result r = cs.take().get();
58 * if (r != null) {
59 * result = r;
60 * break;
61 * }
62 * } catch (ExecutionException ignore) {}
63 * }
64 * } finally {
65 * futures.forEach(future -> future.cancel(true));
66 * }
67 *
68 * if (result != null)
69 * use(result);
70 * }}</pre>
71 *
72 * @since 1.5
73 */
74 public class ExecutorCompletionService<V> implements CompletionService<V> {
75 private final Executor executor;
76 private final AbstractExecutorService aes;
77 private final BlockingQueue<Future<V>> completionQueue;
78
79 /**
80 * FutureTask extension to enqueue upon completion.
81 */
82 private static class QueueingFuture<V> extends FutureTask<Void> {
83 QueueingFuture(RunnableFuture<V> task,
84 BlockingQueue<Future<V>> completionQueue) {
85 super(task, null);
86 this.task = task;
87 this.completionQueue = completionQueue;
88 }
89 private final Future<V> task;
90 private final BlockingQueue<Future<V>> completionQueue;
91 protected void done() { completionQueue.add(task); }
92 }
93
94 private RunnableFuture<V> newTaskFor(Callable<V> task) {
95 if (aes == null)
96 return new FutureTask<V>(task);
97 else
98 return aes.newTaskFor(task);
99 }
100
101 private RunnableFuture<V> newTaskFor(Runnable task, V result) {
102 if (aes == null)
103 return new FutureTask<V>(task, result);
104 else
105 return aes.newTaskFor(task, result);
106 }
107
108 /**
109 * Creates an ExecutorCompletionService using the supplied
110 * executor for base task execution and a
111 * {@link LinkedBlockingQueue} as a completion queue.
112 *
113 * @param executor the executor to use
114 * @throws NullPointerException if executor is {@code null}
115 */
116 public ExecutorCompletionService(Executor executor) {
117 if (executor == null)
118 throw new NullPointerException();
119 this.executor = executor;
120 this.aes = (executor instanceof AbstractExecutorService) ?
121 (AbstractExecutorService) executor : null;
122 this.completionQueue = new LinkedBlockingQueue<Future<V>>();
123 }
124
125 /**
126 * Creates an ExecutorCompletionService using the supplied
127 * executor for base task execution and the supplied queue as its
128 * completion queue.
129 *
130 * @param executor the executor to use
131 * @param completionQueue the queue to use as the completion queue
132 * normally one dedicated for use by this service. This
133 * queue is treated as unbounded -- failed attempted
134 * {@code Queue.add} operations for completed tasks cause
135 * them not to be retrievable.
136 * @throws NullPointerException if executor or completionQueue are {@code null}
137 */
138 public ExecutorCompletionService(Executor executor,
139 BlockingQueue<Future<V>> completionQueue) {
140 if (executor == null || completionQueue == null)
141 throw new NullPointerException();
142 this.executor = executor;
143 this.aes = (executor instanceof AbstractExecutorService) ?
144 (AbstractExecutorService) executor : null;
145 this.completionQueue = completionQueue;
146 }
147
148 /**
149 * @throws RejectedExecutionException {@inheritDoc}
150 * @throws NullPointerException {@inheritDoc}
151 */
152 public Future<V> submit(Callable<V> task) {
153 if (task == null) throw new NullPointerException();
154 RunnableFuture<V> f = newTaskFor(task);
155 executor.execute(new QueueingFuture<V>(f, completionQueue));
156 return f;
157 }
158
159 /**
160 * @throws RejectedExecutionException {@inheritDoc}
161 * @throws NullPointerException {@inheritDoc}
162 */
163 public Future<V> submit(Runnable task, V result) {
164 if (task == null) throw new NullPointerException();
165 RunnableFuture<V> f = newTaskFor(task, result);
166 executor.execute(new QueueingFuture<V>(f, completionQueue));
167 return f;
168 }
169
170 public Future<V> take() throws InterruptedException {
171 return completionQueue.take();
172 }
173
174 public Future<V> poll() {
175 return completionQueue.poll();
176 }
177
178 public Future<V> poll(long timeout, TimeUnit unit)
179 throws InterruptedException {
180 return completionQueue.poll(timeout, unit);
181 }
182
183 }