1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain. Use, modify, and |
4 |
* redistribute this code in any way without acknowledgement. |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
|
10 |
/** |
11 |
* A {@link CompletionService} that uses a supplied {@link Executor} |
12 |
* to execute tasks. |
13 |
*/ |
14 |
public class ExecutorCompletionService<V> implements CompletionService<V> { |
15 |
private final Executor executor; |
16 |
private final LinkedBlockingQueue<Future<V>> cq = |
17 |
new LinkedBlockingQueue<Future<V>>(); |
18 |
|
19 |
/** |
20 |
* FutureTask extension to enqueue upon completion |
21 |
*/ |
22 |
private class QueueingFuture<T> extends FutureTask<T> { |
23 |
QueueingFuture(Callable<T> c) { super(c); } |
24 |
QueueingFuture(Runnable t, T r) { super(t, r); } |
25 |
protected void done() { cq.add((Future<V>)this); } |
26 |
} |
27 |
|
28 |
/** |
29 |
* Creates an ExecutorCompletionService using the supplied |
30 |
* executor for base task execution. Normally, this |
31 |
* executor should be dedicated for use by this service |
32 |
8 @throws NullPointerException if executor is null |
33 |
*/ |
34 |
public ExecutorCompletionService(Executor executor) { |
35 |
if (executor == null) |
36 |
throw new NullPointerException(); |
37 |
this.executor = executor; |
38 |
} |
39 |
|
40 |
|
41 |
/** |
42 |
* Return the {@link Executor} used for base |
43 |
* task execution. This may for example be used to shut |
44 |
* down the service. |
45 |
* @return the executor |
46 |
*/ |
47 |
public Executor getExecutor() { |
48 |
return executor; |
49 |
} |
50 |
|
51 |
public Future<V> submit(Callable<V> task) { |
52 |
QueueingFuture<V> f = new QueueingFuture<V>(task); |
53 |
executor.execute(f); |
54 |
return f; |
55 |
} |
56 |
|
57 |
public Future<V> submit(Runnable task, V result) { |
58 |
QueueingFuture<V> f = new QueueingFuture<V>(task, result); |
59 |
executor.execute(f); |
60 |
return f; |
61 |
} |
62 |
|
63 |
public Future<V> take() throws InterruptedException { |
64 |
return cq.take(); |
65 |
} |
66 |
|
67 |
public Future<V> poll() { |
68 |
return cq.poll(); |
69 |
} |
70 |
|
71 |
public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException { |
72 |
return cq.poll(timeout, unit); |
73 |
} |
74 |
} |
75 |
|
76 |
|