ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.31
Committed: Tue Dec 9 18:38:28 2003 UTC (20 years, 6 months ago) by tim
Branch: MAIN
CVS Tags: JSR166_DEC9_PRE_ES_SUBMIT
Changes since 1.30: +0 -18 lines
Log Message:
Oops, forgot to remove <V> Future<V> execute(Executor, Runnable, V),
which we don't need now that we have Future<?> execute(Executor, Runnable).

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 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 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.2 import java.util.*;
9 dl 1.22 import java.util.concurrent.atomic.AtomicInteger;
10 tim 1.20 import java.security.AccessControlContext;
11     import java.security.AccessController;
12     import java.security.PrivilegedAction;
13     import java.security.PrivilegedExceptionAction;
14 tim 1.1
15     /**
16 dl 1.18 * Factory and utility methods for {@link Executor}, {@link
17 dl 1.25 * ExecutorService}, {@link ThreadFactory}, and {@link Future}
18     * classes defined in this package.
19 tim 1.1 *
20     * @since 1.5
21 dl 1.12 * @author Doug Lea
22 tim 1.1 */
23     public class Executors {
24    
25     /**
26 dl 1.2 * A wrapper class that exposes only the ExecutorService methods
27     * of an implementation.
28 tim 1.6 */
29 jozart 1.11 private static class DelegatedExecutorService implements ExecutorService {
30 dl 1.2 private final ExecutorService e;
31     DelegatedExecutorService(ExecutorService executor) { e = executor; }
32     public void execute(Runnable command) { e.execute(command); }
33     public void shutdown() { e.shutdown(); }
34     public List shutdownNow() { return e.shutdownNow(); }
35     public boolean isShutdown() { return e.isShutdown(); }
36     public boolean isTerminated() { return e.isTerminated(); }
37     public boolean awaitTermination(long timeout, TimeUnit unit)
38     throws InterruptedException {
39     return e.awaitTermination(timeout, unit);
40     }
41     }
42 tim 1.26
43     /**
44     * A wrapper class that exposes only the ExecutorService and
45     * ScheduleExecutor methods of a ScheduledThreadPoolExecutor.
46     */
47 tim 1.27 private static class DelegatedScheduledExecutorService
48 tim 1.28 extends DelegatedExecutorService
49     implements ScheduledExecutorService {
50 tim 1.26 private final ScheduledExecutor e;
51 tim 1.28 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
52 tim 1.26 super(executor);
53     e = executor;
54     }
55 tim 1.30 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
56 tim 1.26 return e.schedule(command, delay, unit);
57     }
58     public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
59     return e.schedule(callable, delay, unit);
60     }
61 tim 1.30 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
62 tim 1.26 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
63     }
64 tim 1.30 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
65 tim 1.26 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
66     }
67     }
68 dl 1.2
69     /**
70 tim 1.1 * Creates a thread pool that reuses a fixed set of threads
71 dl 1.16 * operating off a shared unbounded queue. If any thread
72     * terminates due to a failure during execution prior to shutdown,
73     * a new one will take its place if needed to execute subsequent
74     * tasks.
75 tim 1.1 *
76     * @param nThreads the number of threads in the pool
77     * @return the newly created thread pool
78     */
79 dl 1.2 public static ExecutorService newFixedThreadPool(int nThreads) {
80     return new DelegatedExecutorService
81     (new ThreadPoolExecutor(nThreads, nThreads,
82     0L, TimeUnit.MILLISECONDS,
83 dl 1.3 new LinkedBlockingQueue<Runnable>()));
84 dl 1.2 }
85    
86     /**
87     * Creates a thread pool that reuses a fixed set of threads
88     * operating off a shared unbounded queue, using the provided
89     * ThreadFactory to create new threads when needed.
90     *
91     * @param nThreads the number of threads in the pool
92 dl 1.12 * @param threadFactory the factory to use when creating new threads
93 dl 1.2 * @return the newly created thread pool
94     */
95     public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
96     return new DelegatedExecutorService
97     (new ThreadPoolExecutor(nThreads, nThreads,
98     0L, TimeUnit.MILLISECONDS,
99 dl 1.3 new LinkedBlockingQueue<Runnable>(),
100 dl 1.14 threadFactory));
101 dl 1.2 }
102    
103     /**
104     * Creates an Executor that uses a single worker thread operating
105     * off an unbounded queue. (Note however that if this single
106     * thread terminates due to a failure during execution prior to
107     * shutdown, a new one will take its place if needed to execute
108     * subsequent tasks.) Tasks are guaranteed to execute
109     * sequentially, and no more than one task will be active at any
110 dl 1.16 * given time. This method is equivalent in effect to
111     *<tt>new FixedThreadPool(1)</tt>.
112 dl 1.2 *
113     * @return the newly-created single-threaded Executor
114     */
115     public static ExecutorService newSingleThreadExecutor() {
116     return new DelegatedExecutorService
117 tim 1.6 (new ThreadPoolExecutor(1, 1,
118 dl 1.2 0L, TimeUnit.MILLISECONDS,
119 dl 1.3 new LinkedBlockingQueue<Runnable>()));
120 dl 1.2 }
121    
122     /**
123     * Creates an Executor that uses a single worker thread operating
124     * off an unbounded queue, and uses the provided ThreadFactory to
125     * create new threads when needed.
126 dl 1.12 * @param threadFactory the factory to use when creating new
127 dl 1.2 * threads
128     *
129     * @return the newly-created single-threaded Executor
130     */
131     public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
132     return new DelegatedExecutorService
133 tim 1.6 (new ThreadPoolExecutor(1, 1,
134 dl 1.2 0L, TimeUnit.MILLISECONDS,
135 dl 1.3 new LinkedBlockingQueue<Runnable>(),
136 dl 1.14 threadFactory));
137 tim 1.1 }
138    
139     /**
140     * Creates a thread pool that creates new threads as needed, but
141     * will reuse previously constructed threads when they are
142     * available. These pools will typically improve the performance
143     * of programs that execute many short-lived asynchronous tasks.
144     * Calls to <tt>execute</tt> will reuse previously constructed
145     * threads if available. If no existing thread is available, a new
146     * thread will be created and added to the pool. Threads that have
147     * not been used for sixty seconds are terminated and removed from
148     * the cache. Thus, a pool that remains idle for long enough will
149 dl 1.16 * not consume any resources. Note that pools with similar
150     * properties but different details (for example, timeout parameters)
151     * may be created using {@link ThreadPoolExecutor} constructors.
152 tim 1.1 *
153     * @return the newly created thread pool
154     */
155 dl 1.2 public static ExecutorService newCachedThreadPool() {
156     return new DelegatedExecutorService
157     (new ThreadPoolExecutor(0, Integer.MAX_VALUE,
158     60, TimeUnit.SECONDS,
159 dl 1.3 new SynchronousQueue<Runnable>()));
160 tim 1.1 }
161    
162     /**
163 dl 1.2 * Creates a thread pool that creates new threads as needed, but
164     * will reuse previously constructed threads when they are
165 tim 1.6 * available, and uses the provided
166 dl 1.2 * ThreadFactory to create new threads when needed.
167 dl 1.12 * @param threadFactory the factory to use when creating new threads
168 tim 1.1 * @return the newly created thread pool
169     */
170 dl 1.2 public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
171     return new DelegatedExecutorService
172     (new ThreadPoolExecutor(0, Integer.MAX_VALUE,
173     60, TimeUnit.SECONDS,
174 dl 1.3 new SynchronousQueue<Runnable>(),
175 dl 1.14 threadFactory));
176 tim 1.1 }
177 tim 1.27
178 tim 1.26 /**
179     * Creates a thread pool that can schedule commands to run after a
180     * given delay, or to execute periodically.
181 tim 1.29 * @return a newly created scheduled thread pool with termination management
182 tim 1.26 */
183 tim 1.28 public static ScheduledExecutorService newScheduledThreadPool() {
184 tim 1.27 return newScheduledThreadPool(1);
185 tim 1.26 }
186    
187     /**
188     * Creates a thread pool that can schedule commands to run after a
189     * given delay, or to execute periodically.
190     * @param corePoolSize the number of threads to keep in the pool,
191     * even if they are idle.
192 tim 1.29 * @return a newly created scheduled thread pool with termination management
193 tim 1.26 */
194 tim 1.28 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
195 tim 1.27 return new DelegatedScheduledExecutorService
196     (new ScheduledThreadPoolExecutor(corePoolSize));
197 tim 1.26 }
198    
199     /**
200     * Creates a thread pool that can schedule commands to run after a
201     * given delay, or to execute periodically.
202     * @param corePoolSize the number of threads to keep in the pool,
203     * even if they are idle.
204     * @param threadFactory the factory to use when the executor
205     * creates a new thread.
206 tim 1.29 * @return a newly created scheduled thread pool with termination management
207 tim 1.26 */
208 tim 1.28 public static ScheduledExecutorService newScheduledThreadPool(
209     int corePoolSize, ThreadFactory threadFactory) {
210 tim 1.27 return new DelegatedScheduledExecutorService
211     (new ScheduledThreadPoolExecutor(corePoolSize, threadFactory));
212 tim 1.26 }
213 tim 1.1
214     /**
215 dl 1.25 * Executes a Runnable task and returns a Future representing that
216 tim 1.15 * task.
217     *
218     * @param executor the Executor to which the task will be submitted
219     * @param task the task to submit
220 dl 1.25 * @return a Future representing pending completion of the task,
221 tim 1.30 * and whose <tt>get()</tt> method will return an arbitrary value
222 dl 1.25 * upon completion
223 tim 1.15 * @throws RejectedExecutionException if task cannot be scheduled
224     * for execution
225     */
226 tim 1.30 public static Future<?> execute(Executor executor, Runnable task) {
227     FutureTask<?> ftask = new FutureTask<Boolean>(task, Boolean.TRUE);
228 tim 1.15 executor.execute(ftask);
229     return ftask;
230     }
231    
232     /**
233 tim 1.1 * Executes a value-returning task and returns a Future
234     * representing the pending results of the task.
235     *
236     * @param executor the Executor to which the task will be submitted
237     * @param task the task to submit
238     * @return a Future representing pending completion of the task
239 jozart 1.9 * @throws RejectedExecutionException if task cannot be scheduled
240     * for execution
241 tim 1.1 */
242 tim 1.15 public static <T> Future<T> execute(Executor executor, Callable<T> task) {
243 dl 1.10 FutureTask<T> ftask = new FutureTask<T>(task);
244 tim 1.1 executor.execute(ftask);
245     return ftask;
246     }
247    
248     /**
249     * Executes a Runnable task and blocks until it completes normally
250     * or throws an exception.
251     *
252     * @param executor the Executor to which the task will be submitted
253     * @param task the task to submit
254 jozart 1.9 * @throws RejectedExecutionException if task cannot be scheduled
255     * for execution
256 dl 1.19 * @throws ExecutionException if the task encountered an exception
257     * while executing
258 tim 1.1 */
259     public static void invoke(Executor executor, Runnable task)
260     throws ExecutionException, InterruptedException {
261 tim 1.30 FutureTask<?> ftask = new FutureTask<Boolean>(task, Boolean.TRUE);
262 tim 1.1 executor.execute(ftask);
263     ftask.get();
264     }
265    
266     /**
267     * Executes a value-returning task and blocks until it returns a
268     * value or throws an exception.
269     *
270     * @param executor the Executor to which the task will be submitted
271     * @param task the task to submit
272     * @return a Future representing pending completion of the task
273 jozart 1.9 * @throws RejectedExecutionException if task cannot be scheduled
274     * for execution
275 dl 1.12 * @throws InterruptedException if interrupted while waiting for
276     * completion
277 dl 1.19 * @throws ExecutionException if the task encountered an exception
278     * while executing
279 tim 1.1 */
280     public static <T> T invoke(Executor executor, Callable<T> task)
281     throws ExecutionException, InterruptedException {
282     FutureTask<T> ftask = new FutureTask<T>(task);
283     executor.execute(ftask);
284     return ftask.get();
285 tim 1.6 }
286    
287 tim 1.20
288     /**
289     * Executes a privileged action under the current access control
290     * context and returns a Future representing the pending result
291     * object of that action.
292     *
293     * @param executor the Executor to which the task will be submitted
294     * @param action the action to submit
295     * @return a Future representing pending completion of the action
296     * @throws RejectedExecutionException if action cannot be scheduled
297     * for execution
298     */
299     public static Future<Object> execute(Executor executor, PrivilegedAction action) {
300     Callable<Object> task = new PrivilegedActionAdapter(action);
301 tim 1.21 FutureTask<Object> future = new PrivilegedFutureTask<Object>(task);
302 tim 1.20 executor.execute(future);
303     return future;
304     }
305    
306     /**
307     * Executes a privileged exception action under the current access control
308     * context and returns a Future representing the pending result
309     * object of that action.
310     *
311     * @param executor the Executor to which the task will be submitted
312     * @param action the action to submit
313     * @return a Future representing pending completion of the action
314     * @throws RejectedExecutionException if action cannot be scheduled
315     * for execution
316     */
317     public static Future<Object> execute(Executor executor, PrivilegedExceptionAction action) {
318     Callable<Object> task = new PrivilegedExceptionActionAdapter(action);
319 tim 1.21 FutureTask<Object> future = new PrivilegedFutureTask<Object>(task);
320 tim 1.20 executor.execute(future);
321     return future;
322     }
323    
324     private static class PrivilegedActionAdapter implements Callable<Object> {
325     PrivilegedActionAdapter(PrivilegedAction action) {
326     this.action = action;
327     }
328     public Object call () {
329     return action.run();
330     }
331     private final PrivilegedAction action;
332     }
333    
334     private static class PrivilegedExceptionActionAdapter implements Callable<Object> {
335     PrivilegedExceptionActionAdapter(PrivilegedExceptionAction action) {
336     this.action = action;
337     }
338     public Object call () throws Exception {
339     return action.run();
340     }
341     private final PrivilegedExceptionAction action;
342     }
343    
344 dl 1.22 /**
345     * Return a default thread factory used to create new threads.
346     * This factory creates all new threads used by an Executor in the
347     * same {@link ThreadGroup}. If there is a {@link
348     * java.lang.SecurityManager}, it uses the group of {@link
349     * System#getSecurityManager}, else the group of the thread
350     * invoking this <tt>defaultThreadFactory</tt> method. Each new
351     * thread is created as a non-daemon thread with priority
352     * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
353     * accessible via {@link Thread#getName} of
354     * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
355     * number of this factory, and <em>M</em> is the sequence number
356     * of the thread created by this factory.
357     * @return the thread factory
358     */
359     public static ThreadFactory defaultThreadFactory() {
360 tim 1.26 return new DefaultThreadFactory();
361 dl 1.22 }
362    
363     /**
364 dl 1.24 * Return a thread factory used to create new threads that
365     * have the same permissions as the current thread.
366 dl 1.22 * This factory creates threads with the same settings as {@link
367     * Executors#defaultThreadFactory}, additionally setting the
368     * AccessControlContext and contextClassLoader of new threads to
369     * be the same as the thread invoking this
370     * <tt>privilegedThreadFactory</tt> method. A new
371     * <tt>privilegedThreadFactory</tt> can be created within an
372 dl 1.23 * {@link AccessController#doPrivileged} action setting the
373 dl 1.24 * current thread's access control context to create threads with
374 dl 1.23 * the selected permission settings holding within that action.
375 dl 1.22 *
376     * <p> Note that while tasks running within such threads will have
377     * the same access control and class loader settings as the
378     * current thread, they need not have the same {@link
379     * java.lang.ThreadLocal} or {@link
380     * java.lang.InheritableThreadLocal} values. If necessary,
381     * particular values of thread locals can be set or reset before
382     * any task runs in {@link ThreadPoolExecutor} subclasses using
383     * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
384     * necessary to initialize worker threads to have the same
385     * InheritableThreadLocal settings as some other designated
386     * thread, you can create a custom ThreadFactory in which that
387     * thread waits for and services requests to create others that
388     * will inherit its values.
389     *
390     * @return the thread factory
391     * @throws AccessControlException if the current access control
392     * context does not have permission to both get and set context
393     * class loader.
394     * @see PrivilegedFutureTask
395     */
396     public static ThreadFactory privilegedThreadFactory() {
397 tim 1.26 return new PrivilegedThreadFactory();
398 dl 1.22 }
399    
400     static class DefaultThreadFactory implements ThreadFactory {
401 tim 1.26 static final AtomicInteger poolNumber = new AtomicInteger(1);
402     final ThreadGroup group;
403     final AtomicInteger threadNumber = new AtomicInteger(1);
404     final String namePrefix;
405 dl 1.22
406 tim 1.26 DefaultThreadFactory() {
407 dl 1.22 SecurityManager s = System.getSecurityManager();
408     group = (s != null)? s.getThreadGroup() :
409     Thread.currentThread().getThreadGroup();
410     namePrefix = "pool-" +
411     poolNumber.getAndIncrement() +
412     "-thread-";
413     }
414    
415     public Thread newThread(Runnable r) {
416     Thread t = new Thread(group, r,
417     namePrefix + threadNumber.getAndIncrement(),
418     0);
419     if (t.isDaemon())
420     t.setDaemon(false);
421     if (t.getPriority() != Thread.NORM_PRIORITY)
422     t.setPriority(Thread.NORM_PRIORITY);
423     return t;
424     }
425     }
426    
427     static class PrivilegedThreadFactory extends DefaultThreadFactory {
428     private final ClassLoader ccl;
429     private final AccessControlContext acc;
430    
431     PrivilegedThreadFactory() {
432     super();
433     this.ccl = Thread.currentThread().getContextClassLoader();
434     this.acc = AccessController.getContext();
435     acc.checkPermission(new RuntimePermission("setContextClassLoader"));
436     }
437    
438     public Thread newThread(final Runnable r) {
439     return super.newThread(new Runnable() {
440     public void run() {
441     AccessController.doPrivileged(new PrivilegedAction() {
442     public Object run() {
443     Thread.currentThread().setContextClassLoader(ccl);
444     r.run();
445     return null;
446     }
447     }, acc);
448     }
449     });
450     }
451    
452     }
453    
454 tim 1.20
455 tim 1.15 /** Cannot instantiate. */
456     private Executors() {}
457 tim 1.1 }