ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorCompletionService.java
Revision: 1.22
Committed: Sun May 25 02:41:29 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.21: +32 -33 lines
Log Message:
use 2-space indent in code samples

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> ecs
31 * = new ExecutorCompletionService<Result>(e);
32 * for (Callable<Result> s : solvers)
33 * ecs.submit(s);
34 * int n = solvers.size();
35 * for (int i = 0; i < n; ++i) {
36 * Result r = ecs.take().get();
37 * if (r != null)
38 * use(r);
39 * }
40 * }}</pre>
41 *
42 * Suppose instead that you would like to use the first non-null result
43 * of the set of tasks, ignoring any that encounter exceptions,
44 * and cancelling all other tasks when the first one is ready:
45 *
46 * <pre> {@code
47 * void solve(Executor e,
48 * Collection<Callable<Result>> solvers)
49 * throws InterruptedException {
50 * CompletionService<Result> ecs
51 * = new ExecutorCompletionService<Result>(e);
52 * int n = solvers.size();
53 * List<Future<Result>> futures = new ArrayList<>(n);
54 * Result result = null;
55 * try {
56 * for (Callable<Result> s : solvers)
57 * futures.add(ecs.submit(s));
58 * for (int i = 0; i < n; ++i) {
59 * try {
60 * Result r = ecs.take().get();
61 * if (r != null) {
62 * result = r;
63 * break;
64 * }
65 * } catch (ExecutionException ignore) {}
66 * }
67 * }
68 * finally {
69 * for (Future<Result> f : futures)
70 * f.cancel(true);
71 * }
72 *
73 * if (result != null)
74 * use(result);
75 * }}</pre>
76 */
77 public class ExecutorCompletionService<V> implements CompletionService<V> {
78 private final Executor executor;
79 private final AbstractExecutorService aes;
80 private final BlockingQueue<Future<V>> completionQueue;
81
82 /**
83 * FutureTask extension to enqueue upon completion
84 */
85 private class QueueingFuture extends FutureTask<Void> {
86 QueueingFuture(RunnableFuture<V> task) {
87 super(task, null);
88 this.task = task;
89 }
90 protected void done() { completionQueue.add(task); }
91 private final Future<V> 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 public Future<V> submit(Callable<V> task) {
149 if (task == null) throw new NullPointerException();
150 RunnableFuture<V> f = newTaskFor(task);
151 executor.execute(new QueueingFuture(f));
152 return f;
153 }
154
155 public Future<V> submit(Runnable task, V result) {
156 if (task == null) throw new NullPointerException();
157 RunnableFuture<V> f = newTaskFor(task, result);
158 executor.execute(new QueueingFuture(f));
159 return f;
160 }
161
162 public Future<V> take() throws InterruptedException {
163 return completionQueue.take();
164 }
165
166 public Future<V> poll() {
167 return completionQueue.poll();
168 }
169
170 public Future<V> poll(long timeout, TimeUnit unit)
171 throws InterruptedException {
172 return completionQueue.poll(timeout, unit);
173 }
174
175 }