ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.56
Committed: Thu May 26 12:07:14 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.55: +6 -31 lines
Log Message:
Avoid some generics cast warnings

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/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8 import java.util.*;
9 import java.util.concurrent.atomic.AtomicInteger;
10 import java.security.AccessControlContext;
11 import java.security.AccessController;
12 import java.security.PrivilegedAction;
13 import java.security.PrivilegedExceptionAction;
14 import java.security.AccessControlException;
15
16 /**
17 * Factory and utility methods for {@link Executor}, {@link
18 * ExecutorService}, {@link ScheduledExecutorService}, {@link
19 * ThreadFactory}, and {@link Callable} classes defined in this
20 * package. This class supports the following kinds of methods:
21 *
22 * <ul>
23 * <li> Methods that create and return an {@link ExecutorService}
24 * set up with commonly useful configuration settings.
25 * <li> Methods that create and return a {@link ScheduledExecutorService}
26 * set up with commonly useful configuration settings.
27 * <li> Methods that create and return a "wrapped" ExecutorService, that
28 * disables reconfiguration by making implementation-specific methods
29 * inaccessible.
30 * <li> Methods that create and return a {@link ThreadFactory}
31 * that sets newly created threads to a known state.
32 * <li> Methods that create and return a {@link Callable}
33 * out of other closure-like forms, so they can be used
34 * in execution methods requiring <tt>Callable</tt>.
35 * </ul>
36 *
37 * @since 1.5
38 * @author Doug Lea
39 */
40 public class Executors {
41
42 /**
43 * Creates a thread pool that reuses a fixed set of threads
44 * operating off a shared unbounded queue. If any thread
45 * terminates due to a failure during execution prior to shutdown,
46 * a new one will take its place if needed to execute subsequent
47 * tasks.
48 *
49 * @param nThreads the number of threads in the pool
50 * @return the newly created thread pool
51 */
52 public static ExecutorService newFixedThreadPool(int nThreads) {
53 return new ThreadPoolExecutor(nThreads, nThreads,
54 0L, TimeUnit.MILLISECONDS,
55 new LinkedBlockingQueue<Runnable>());
56 }
57
58 /**
59 * Creates a thread pool that reuses a fixed set of threads
60 * operating off a shared unbounded queue, using the provided
61 * ThreadFactory to create new threads when needed.
62 *
63 * @param nThreads the number of threads in the pool
64 * @param threadFactory the factory to use when creating new threads
65 * @return the newly created thread pool
66 */
67 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
68 return new ThreadPoolExecutor(nThreads, nThreads,
69 0L, TimeUnit.MILLISECONDS,
70 new LinkedBlockingQueue<Runnable>(),
71 threadFactory);
72 }
73
74 /**
75 * Creates an Executor that uses a single worker thread operating
76 * off an unbounded queue. (Note however that if this single
77 * thread terminates due to a failure during execution prior to
78 * shutdown, a new one will take its place if needed to execute
79 * subsequent tasks.) Tasks are guaranteed to execute
80 * sequentially, and no more than one task will be active at any
81 * given time. Unlike the otherwise equivalent
82 * <tt>newFixedThreadPool(1)</tt> the returned executor is
83 * guaranteed not to be reconfigurable to use additional threads.
84 *
85 * @return the newly created single-threaded Executor
86 */
87 public static ExecutorService newSingleThreadExecutor() {
88 return new DelegatedExecutorService
89 (new ThreadPoolExecutor(1, 1,
90 0L, TimeUnit.MILLISECONDS,
91 new LinkedBlockingQueue<Runnable>()));
92 }
93
94 /**
95 * Creates an Executor that uses a single worker thread operating
96 * off an unbounded queue, and uses the provided ThreadFactory to
97 * create a new thread when needed. Unlike the otherwise
98 * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the returned executor
99 * is guaranteed not to be reconfigurable to use additional
100 * threads.
101 *
102 * @param threadFactory the factory to use when creating new
103 * threads
104 *
105 * @return the newly created single-threaded Executor
106 */
107 public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
108 return new DelegatedExecutorService
109 (new ThreadPoolExecutor(1, 1,
110 0L, TimeUnit.MILLISECONDS,
111 new LinkedBlockingQueue<Runnable>(),
112 threadFactory));
113 }
114
115 /**
116 * Creates a thread pool that creates new threads as needed, but
117 * will reuse previously constructed threads when they are
118 * available. These pools will typically improve the performance
119 * of programs that execute many short-lived asynchronous tasks.
120 * Calls to <tt>execute</tt> will reuse previously constructed
121 * threads if available. If no existing thread is available, a new
122 * thread will be created and added to the pool. Threads that have
123 * not been used for sixty seconds are terminated and removed from
124 * the cache. Thus, a pool that remains idle for long enough will
125 * not consume any resources. Note that pools with similar
126 * properties but different details (for example, timeout parameters)
127 * may be created using {@link ThreadPoolExecutor} constructors.
128 *
129 * @return the newly created thread pool
130 */
131 public static ExecutorService newCachedThreadPool() {
132 return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
133 60L, TimeUnit.SECONDS,
134 new SynchronousQueue<Runnable>());
135 }
136
137 /**
138 * Creates a thread pool that creates new threads as needed, but
139 * will reuse previously constructed threads when they are
140 * available, and uses the provided
141 * ThreadFactory to create new threads when needed.
142 * @param threadFactory the factory to use when creating new threads
143 * @return the newly created thread pool
144 */
145 public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
146 return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
147 60L, TimeUnit.SECONDS,
148 new SynchronousQueue<Runnable>(),
149 threadFactory);
150 }
151
152 /**
153 * Creates a single-threaded executor that can schedule commands
154 * to run after a given delay, or to execute periodically.
155 * (Note however that if this single
156 * thread terminates due to a failure during execution prior to
157 * shutdown, a new one will take its place if needed to execute
158 * subsequent tasks.) Tasks are guaranteed to execute
159 * sequentially, and no more than one task will be active at any
160 * given time. Unlike the otherwise equivalent
161 * <tt>newScheduledThreadPool(1)</tt> the returned executor is
162 * guaranteed not to be reconfigurable to use additional threads.
163 * @return the newly created scheduled executor
164 */
165 public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
166 return new DelegatedScheduledExecutorService
167 (new ScheduledThreadPoolExecutor(1));
168 }
169
170 /**
171 * Creates a single-threaded executor that can schedule commands
172 * to run after a given delay, or to execute periodically. (Note
173 * however that if this single thread terminates due to a failure
174 * during execution prior to shutdown, a new one will take its
175 * place if needed to execute subsequent tasks.) Tasks are
176 * guaranteed to execute sequentially, and no more than one task
177 * will be active at any given time. Unlike the otherwise
178 * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
179 * the returned executor is guaranteed not to be reconfigurable to
180 * use additional threads.
181 * @param threadFactory the factory to use when creating new
182 * threads
183 * @return a newly created scheduled executor
184 */
185 public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
186 return new DelegatedScheduledExecutorService
187 (new ScheduledThreadPoolExecutor(1, threadFactory));
188 }
189
190 /**
191 * Creates a thread pool that can schedule commands to run after a
192 * given delay, or to execute periodically.
193 * @param corePoolSize the number of threads to keep in the pool,
194 * even if they are idle.
195 * @return a newly created scheduled thread pool
196 */
197 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
198 return new ScheduledThreadPoolExecutor(corePoolSize);
199 }
200
201 /**
202 * Creates a thread pool that can schedule commands to run after a
203 * given delay, or to execute periodically.
204 * @param corePoolSize the number of threads to keep in the pool,
205 * even if they are idle.
206 * @param threadFactory the factory to use when the executor
207 * creates a new thread.
208 * @return a newly created scheduled thread pool
209 */
210 public static ScheduledExecutorService newScheduledThreadPool(
211 int corePoolSize, ThreadFactory threadFactory) {
212 return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
213 }
214
215
216 /**
217 * Returns an object that delegates all defined {@link
218 * ExecutorService} methods to the given executor, but not any
219 * other methods that might otherwise be accessible using
220 * casts. This provides a way to safely "freeze" configuration and
221 * disallow tuning of a given concrete implementation.
222 * @param executor the underlying implementation
223 * @return an <tt>ExecutorService</tt> instance
224 * @throws NullPointerException if executor null
225 */
226 public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
227 if (executor == null)
228 throw new NullPointerException();
229 return new DelegatedExecutorService(executor);
230 }
231
232 /**
233 * Returns an object that delegates all defined {@link
234 * ScheduledExecutorService} methods to the given executor, but
235 * not any other methods that might otherwise be accessible using
236 * casts. This provides a way to safely "freeze" configuration and
237 * disallow tuning of a given concrete implementation.
238 * @param executor the underlying implementation
239 * @return a <tt>ScheduledExecutorService</tt> instance
240 * @throws NullPointerException if executor null
241 */
242 public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
243 if (executor == null)
244 throw new NullPointerException();
245 return new DelegatedScheduledExecutorService(executor);
246 }
247
248 /**
249 * Returns a default thread factory used to create new threads.
250 * This factory creates all new threads used by an Executor in the
251 * same {@link ThreadGroup}. If there is a {@link
252 * java.lang.SecurityManager}, it uses the group of {@link
253 * System#getSecurityManager}, else the group of the thread
254 * invoking this <tt>defaultThreadFactory</tt> method. Each new
255 * thread is created as a non-daemon thread with priority set to
256 * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum
257 * priority permitted in the thread group. New threads have names
258 * accessible via {@link Thread#getName} of
259 * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
260 * number of this factory, and <em>M</em> is the sequence number
261 * of the thread created by this factory.
262 * @return a thread factory
263 */
264 public static ThreadFactory defaultThreadFactory() {
265 return new DefaultThreadFactory();
266 }
267
268 /**
269 * Returns a thread factory used to create new threads that
270 * have the same permissions as the current thread.
271 * This factory creates threads with the same settings as {@link
272 * Executors#defaultThreadFactory}, additionally setting the
273 * AccessControlContext and contextClassLoader of new threads to
274 * be the same as the thread invoking this
275 * <tt>privilegedThreadFactory</tt> method. A new
276 * <tt>privilegedThreadFactory</tt> can be created within an
277 * {@link AccessController#doPrivileged} action setting the
278 * current thread's access control context to create threads with
279 * the selected permission settings holding within that action.
280 *
281 * <p> Note that while tasks running within such threads will have
282 * the same access control and class loader settings as the
283 * current thread, they need not have the same {@link
284 * java.lang.ThreadLocal} or {@link
285 * java.lang.InheritableThreadLocal} values. If necessary,
286 * particular values of thread locals can be set or reset before
287 * any task runs in {@link ThreadPoolExecutor} subclasses using
288 * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
289 * necessary to initialize worker threads to have the same
290 * InheritableThreadLocal settings as some other designated
291 * thread, you can create a custom ThreadFactory in which that
292 * thread waits for and services requests to create others that
293 * will inherit its values.
294 *
295 * @return a thread factory
296 * @throws AccessControlException if the current access control
297 * context does not have permission to both get and set context
298 * class loader.
299 */
300 public static ThreadFactory privilegedThreadFactory() {
301 return new PrivilegedThreadFactory();
302 }
303
304 /**
305 * Returns a {@link Callable} object that, when
306 * called, runs the given task and returns the given result. This
307 * can be useful when applying methods requiring a
308 * <tt>Callable</tt> to an otherwise resultless action.
309 * @param task the task to run
310 * @param result the result to return
311 * @throws NullPointerException if task null
312 * @return a callable object
313 */
314 public static <T> Callable<T> callable(Runnable task, T result) {
315 if (task == null)
316 throw new NullPointerException();
317 return new RunnableAdapter<T>(task, result);
318 }
319
320 /**
321 * Returns a {@link Callable} object that, when
322 * called, runs the given task and returns <tt>null</tt>.
323 * @param task the task to run
324 * @return a callable object
325 * @throws NullPointerException if task null
326 */
327 public static Callable<Object> callable(Runnable task) {
328 if (task == null)
329 throw new NullPointerException();
330 return new RunnableAdapter<Object>(task, null);
331 }
332
333 /**
334 * Returns a {@link Callable} object that, when
335 * called, runs the given privileged action and returns its result.
336 * @param action the privileged action to run
337 * @return a callable object
338 * @throws NullPointerException if action null
339 */
340 public static Callable<Object> callable(final PrivilegedAction<?> action) {
341 if (action == null)
342 throw new NullPointerException();
343 return new Callable<Object>() {
344 public Object call() { return action.run(); }};
345 }
346
347 /**
348 * Returns a {@link Callable} object that, when
349 * called, runs the given privileged exception action and returns
350 * its result.
351 * @param action the privileged exception action to run
352 * @return a callable object
353 * @throws NullPointerException if action null
354 */
355 public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
356 if (action == null)
357 throw new NullPointerException();
358 return new Callable<Object>() {
359 public Object call() throws Exception { return action.run(); }};
360 }
361
362 /**
363 * Returns a {@link Callable} object that will, when
364 * called, execute the given <tt>callable</tt> under the current
365 * access control context. This method should normally be
366 * invoked within an {@link AccessController#doPrivileged} action
367 * to create callables that will, if possible, execute under the
368 * selected permission settings holding within that action; or if
369 * not possible, throw an associated {@link
370 * AccessControlException}.
371 * @param callable the underlying task
372 * @return a callable object
373 * @throws NullPointerException if callable null
374 *
375 */
376 public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
377 if (callable == null)
378 throw new NullPointerException();
379 return new PrivilegedCallable<T>(callable);
380 }
381
382 /**
383 * Returns a {@link Callable} object that will, when
384 * called, execute the given <tt>callable</tt> under the current
385 * access control context, with the current context class loader
386 * as the context class loader. This method should normally be
387 * invoked within an {@link AccessController#doPrivileged} action
388 * to create callables that will, if possible, execute under the
389 * selected permission settings holding within that action; or if
390 * not possible, throw an associated {@link
391 * AccessControlException}.
392 * @param callable the underlying task
393 *
394 * @return a callable object
395 * @throws NullPointerException if callable null
396 * @throws AccessControlException if the current access control
397 * context does not have permission to both set and get context
398 * class loader.
399 */
400 public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
401 if (callable == null)
402 throw new NullPointerException();
403 return new PrivilegedCallableUsingCurrentClassLoader<T>(callable);
404 }
405
406 // Non-public classes supporting the public methods
407
408 /**
409 * A callable that runs given task and returns given result
410 */
411 static final class RunnableAdapter<T> implements Callable<T> {
412 final Runnable task;
413 final T result;
414 RunnableAdapter(Runnable task, T result) {
415 this.task = task;
416 this.result = result;
417 }
418 public T call() {
419 task.run();
420 return result;
421 }
422 }
423
424 /**
425 * A callable that runs under established access control settings
426 */
427 static final class PrivilegedCallable<T> implements Callable<T> {
428 private final AccessControlContext acc;
429 private final Callable<T> task;
430 private T result;
431 private Exception exception;
432 PrivilegedCallable(Callable<T> task) {
433 this.task = task;
434 this.acc = AccessController.getContext();
435 }
436
437 public T call() throws Exception {
438 AccessController.doPrivileged(new PrivilegedAction<T>() {
439 public T run() {
440 try {
441 result = task.call();
442 } catch (Exception ex) {
443 exception = ex;
444 }
445 return null;
446 }
447 }, acc);
448 if (exception != null)
449 throw exception;
450 else
451 return result;
452 }
453 }
454
455 /**
456 * A callable that runs under established access control settings and
457 * current ClassLoader
458 */
459 static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
460 private final ClassLoader ccl;
461 private final AccessControlContext acc;
462 private final Callable<T> task;
463 private T result;
464 private Exception exception;
465 PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
466 this.task = task;
467 this.ccl = Thread.currentThread().getContextClassLoader();
468 this.acc = AccessController.getContext();
469 acc.checkPermission(new RuntimePermission("getContextClassLoader"));
470 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
471 }
472
473 public T call() throws Exception {
474 AccessController.doPrivileged(new PrivilegedAction<T>() {
475 public T run() {
476 ClassLoader savedcl = null;
477 Thread t = Thread.currentThread();
478 try {
479 ClassLoader cl = t.getContextClassLoader();
480 if (ccl != cl) {
481 t.setContextClassLoader(ccl);
482 savedcl = cl;
483 }
484 result = task.call();
485 } catch (Exception ex) {
486 exception = ex;
487 } finally {
488 if (savedcl != null)
489 t.setContextClassLoader(savedcl);
490 }
491 return null;
492 }
493 }, acc);
494 if (exception != null)
495 throw exception;
496 else
497 return result;
498 }
499 }
500
501 /**
502 * The default thread factory
503 */
504 static class DefaultThreadFactory implements ThreadFactory {
505 static final AtomicInteger poolNumber = new AtomicInteger(1);
506 final ThreadGroup group;
507 final AtomicInteger threadNumber = new AtomicInteger(1);
508 final String namePrefix;
509
510 DefaultThreadFactory() {
511 SecurityManager s = System.getSecurityManager();
512 group = (s != null)? s.getThreadGroup() :
513 Thread.currentThread().getThreadGroup();
514 namePrefix = "pool-" +
515 poolNumber.getAndIncrement() +
516 "-thread-";
517 }
518
519 public Thread newThread(Runnable r) {
520 Thread t = new Thread(group, r,
521 namePrefix + threadNumber.getAndIncrement(),
522 0);
523 if (t.isDaemon())
524 t.setDaemon(false);
525 if (t.getPriority() != Thread.NORM_PRIORITY)
526 t.setPriority(Thread.NORM_PRIORITY);
527 return t;
528 }
529 }
530
531 /**
532 * Thread factory capturing access control and class loader
533 */
534 static class PrivilegedThreadFactory extends DefaultThreadFactory {
535 private final ClassLoader ccl;
536 private final AccessControlContext acc;
537
538 PrivilegedThreadFactory() {
539 super();
540 this.ccl = Thread.currentThread().getContextClassLoader();
541 this.acc = AccessController.getContext();
542 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
543 }
544
545 public Thread newThread(final Runnable r) {
546 return super.newThread(new Runnable() {
547 public void run() {
548 AccessController.doPrivileged(new PrivilegedAction<Object>() {
549 public Object run() {
550 Thread.currentThread().setContextClassLoader(ccl);
551 r.run();
552 return null;
553 }
554 }, acc);
555 }
556 });
557 }
558
559 }
560
561 /**
562 * A wrapper class that exposes only the ExecutorService methods
563 * of an implementation.
564 */
565 static class DelegatedExecutorService extends AbstractExecutorService {
566 private final ExecutorService e;
567 DelegatedExecutorService(ExecutorService executor) { e = executor; }
568 public void execute(Runnable command) { e.execute(command); }
569 public void shutdown() { e.shutdown(); }
570 public List<Runnable> shutdownNow() { return e.shutdownNow(); }
571 public boolean isShutdown() { return e.isShutdown(); }
572 public boolean isTerminated() { return e.isTerminated(); }
573 public boolean awaitTermination(long timeout, TimeUnit unit)
574 throws InterruptedException {
575 return e.awaitTermination(timeout, unit);
576 }
577 public Future<?> submit(Runnable task) {
578 return e.submit(task);
579 }
580 public <T> Future<T> submit(Callable<T> task) {
581 return e.submit(task);
582 }
583 public <T> Future<T> submit(Runnable task, T result) {
584 return e.submit(task, result);
585 }
586 public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
587 throws InterruptedException {
588 return e.invokeAll(tasks);
589 }
590 public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks,
591 long timeout, TimeUnit unit)
592 throws InterruptedException {
593 return e.invokeAll(tasks, timeout, unit);
594 }
595 public <T> T invokeAny(Collection<Callable<T>> tasks)
596 throws InterruptedException, ExecutionException {
597 return e.invokeAny(tasks);
598 }
599 public <T> T invokeAny(Collection<Callable<T>> tasks,
600 long timeout, TimeUnit unit)
601 throws InterruptedException, ExecutionException, TimeoutException {
602 return e.invokeAny(tasks, timeout, unit);
603 }
604 }
605
606 /**
607 * A wrapper class that exposes only the ExecutorService and
608 * ScheduleExecutor methods of a ScheduledExecutorService implementation.
609 */
610 static class DelegatedScheduledExecutorService
611 extends DelegatedExecutorService
612 implements ScheduledExecutorService {
613 private final ScheduledExecutorService e;
614 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
615 super(executor);
616 e = executor;
617 }
618 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
619 return e.schedule(command, delay, unit);
620 }
621 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
622 return e.schedule(callable, delay, unit);
623 }
624 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
625 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
626 }
627 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
628 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
629 }
630 }
631
632
633 /** Cannot instantiate. */
634 private Executors() {}
635 }