ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorCompletionService.java
Revision: 1.19
Committed: Fri Oct 22 05:49:04 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.18: +2 -1 lines
Log Message:
80 cols

File Contents

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