KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > AbstractExecutorService


1 /*
2  * @(#)AbstractExecutorService.java 1.1 04/02/09
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util.concurrent;
9
10 import java.util.*;
11
12 /**
13  * Provides default implementation of {@link ExecutorService}
14  * execution methods. This class implements the <tt>submit</tt>,
15  * <tt>invokeAny</tt> and <tt>invokeAll</tt> methods using the default
16  * {@link FutureTask} class provided in this package. For example,
17  * the implementation of <tt>submit(Runnable)</tt> creates an
18  * associated <tt>FutureTask</tt> that is executed and
19  * returned. Subclasses overriding these methods to use different
20  * {@link Future} implementations should do so consistently for each
21  * of these methods.
22  *
23  * @since 1.5
24  * @author Doug Lea
25  */

26 public abstract class AbstractExecutorService implements ExecutorService JavaDoc {
27
28     public Future JavaDoc<?> submit(Runnable JavaDoc task) {
29         if (task == null) throw new NullPointerException JavaDoc();
30         FutureTask JavaDoc<Object JavaDoc> ftask = new FutureTask JavaDoc<Object JavaDoc>(task, null);
31         execute(ftask);
32         return ftask;
33     }
34
35     public <T> Future JavaDoc<T> submit(Runnable JavaDoc task, T result) {
36         if (task == null) throw new NullPointerException JavaDoc();
37         FutureTask JavaDoc<T> ftask = new FutureTask JavaDoc<T>(task, result);
38         execute(ftask);
39         return ftask;
40     }
41
42     public <T> Future JavaDoc<T> submit(Callable JavaDoc<T> task) {
43         if (task == null) throw new NullPointerException JavaDoc();
44         FutureTask JavaDoc<T> ftask = new FutureTask JavaDoc<T>(task);
45         execute(ftask);
46         return ftask;
47     }
48
49     /**
50      * the main mechanics of invokeAny.
51      */

52     private <T> T doInvokeAny(Collection<Callable JavaDoc<T>> tasks,
53                             boolean timed, long nanos)
54         throws InterruptedException JavaDoc, ExecutionException JavaDoc, TimeoutException JavaDoc {
55         if (tasks == null)
56             throw new NullPointerException JavaDoc();
57         int ntasks = tasks.size();
58         if (ntasks == 0)
59             throw new IllegalArgumentException JavaDoc();
60         List<Future JavaDoc<T>> futures= new ArrayList<Future JavaDoc<T>>(ntasks);
61         ExecutorCompletionService JavaDoc<T> ecs =
62             new ExecutorCompletionService JavaDoc<T>(this);
63
64         // For efficiency, especially in executors with limited
65
// parallelism, check to see if previously submitted tasks are
66
// done before submitting more of them. This interleaving
67
// plus the exception mechanics account for messiness of main
68
// loop.
69

70         try {
71             // Record exceptions so that if we fail to obtain any
72
// result, we can throw the last exception we got.
73
ExecutionException JavaDoc ee = null;
74             long lastTime = (timed)? System.nanoTime() : 0;
75             Iterator<Callable JavaDoc<T>> it = tasks.iterator();
76
77             // Start one task for sure; the rest incrementally
78
futures.add(ecs.submit(it.next()));
79             --ntasks;
80             int active = 1;
81
82             for (;;) {
83                 Future JavaDoc<T> f = ecs.poll();
84                 if (f == null) {
85                     if (ntasks > 0) {
86                         --ntasks;
87                         futures.add(ecs.submit(it.next()));
88                         ++active;
89                     }
90                     else if (active == 0)
91                         break;
92                     else if (timed) {
93                         f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
94                         if (f == null)
95                             throw new TimeoutException JavaDoc();
96                         long now = System.nanoTime();
97                         nanos -= now - lastTime;
98                         lastTime = now;
99                     }
100                     else
101                         f = ecs.take();
102                 }
103                 if (f != null) {
104                     --active;
105                     try {
106                         return f.get();
107                     } catch(InterruptedException JavaDoc ie) {
108                         throw ie;
109                     } catch(ExecutionException JavaDoc eex) {
110                         ee = eex;
111                     } catch(RuntimeException JavaDoc rex) {
112                         ee = new ExecutionException JavaDoc(rex);
113                     }
114                 }
115             }
116
117             if (ee == null)
118                 ee = new ExecutionException JavaDoc();
119             throw ee;
120
121         } finally {
122             for (Future JavaDoc<T> f : futures)
123                 f.cancel(true);
124         }
125     }
126
127     public <T> T invokeAny(Collection<Callable JavaDoc<T>> tasks)
128         throws InterruptedException JavaDoc, ExecutionException JavaDoc {
129         try {
130             return doInvokeAny(tasks, false, 0);
131         } catch (TimeoutException JavaDoc cannotHappen) {
132             assert false;
133             return null;
134         }
135     }
136
137     public <T> T invokeAny(Collection<Callable JavaDoc<T>> tasks,
138                            long timeout, TimeUnit JavaDoc unit)
139         throws InterruptedException JavaDoc, ExecutionException JavaDoc, TimeoutException JavaDoc {
140         return doInvokeAny(tasks, true, unit.toNanos(timeout));
141     }
142
143     public <T> List<Future JavaDoc<T>> invokeAll(Collection<Callable JavaDoc<T>> tasks)
144         throws InterruptedException JavaDoc {
145         if (tasks == null)
146             throw new NullPointerException JavaDoc();
147         List<Future JavaDoc<T>> futures = new ArrayList<Future JavaDoc<T>>(tasks.size());
148         boolean done = false;
149         try {
150             for (Callable JavaDoc<T> t : tasks) {
151                 FutureTask JavaDoc<T> f = new FutureTask JavaDoc<T>(t);
152                 futures.add(f);
153                 execute(f);
154             }
155             for (Future JavaDoc<T> f : futures) {
156                 if (!f.isDone()) {
157                     try {
158                         f.get();
159                     } catch(CancellationException JavaDoc ignore) {
160                     } catch(ExecutionException JavaDoc ignore) {
161                     }
162                 }
163             }
164             done = true;
165             return futures;
166         } finally {
167             if (!done)
168                 for (Future JavaDoc<T> f : futures)
169                     f.cancel(true);
170         }
171     }
172
173     public <T> List<Future JavaDoc<T>> invokeAll(Collection<Callable JavaDoc<T>> tasks,
174                                          long timeout, TimeUnit JavaDoc unit)
175         throws InterruptedException JavaDoc {
176         if (tasks == null || unit == null)
177             throw new NullPointerException JavaDoc();
178         long nanos = unit.toNanos(timeout);
179         List<Future JavaDoc<T>> futures = new ArrayList<Future JavaDoc<T>>(tasks.size());
180         boolean done = false;
181         try {
182             for (Callable JavaDoc<T> t : tasks)
183                 futures.add(new FutureTask JavaDoc<T>(t));
184
185             long lastTime = System.nanoTime();
186
187             // Interleave time checks and calls to execute in case
188
// executor doesn't have any/much parallelism.
189
Iterator<Future JavaDoc<T>> it = futures.iterator();
190             while (it.hasNext()) {
191                 execute((Runnable JavaDoc)(it.next()));
192                 long now = System.nanoTime();
193                 nanos -= now - lastTime;
194                 lastTime = now;
195                 if (nanos <= 0)
196                     return futures;
197             }
198
199             for (Future JavaDoc<T> f : futures) {
200                 if (!f.isDone()) {
201                     if (nanos <= 0)
202                         return futures;
203                     try {
204                         f.get(nanos, TimeUnit.NANOSECONDS);
205                     } catch(CancellationException JavaDoc ignore) {
206                     } catch(ExecutionException JavaDoc ignore) {
207                     } catch(TimeoutException JavaDoc toe) {
208                         return futures;
209                     }
210                     long now = System.nanoTime();
211                     nanos -= now - lastTime;
212                     lastTime = now;
213                 }
214             }
215             done = true;
216             return futures;
217         } finally {
218             if (!done)
219                 for (Future JavaDoc<T> f : futures)
220                     f.cancel(true);
221         }
222     }
223
224 }
225
Popular Tags