ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.50
Committed: Mon Feb 9 13:28:48 2004 UTC (20 years, 3 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_PFD
Changes since 1.49: +3 -2 lines
Log Message:
Wording fixes and improvements

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
256 * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
257 * accessible via {@link Thread#getName} of
258 * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
259 * number of this factory, and <em>M</em> is the sequence number
260 * of the thread created by this factory.
261 * @return a thread factory
262 */
263 public static ThreadFactory defaultThreadFactory() {
264 return new DefaultThreadFactory();
265 }
266
267 /**
268 * Returns a thread factory used to create new threads that
269 * have the same permissions as the current thread.
270 * This factory creates threads with the same settings as {@link
271 * Executors#defaultThreadFactory}, additionally setting the
272 * AccessControlContext and contextClassLoader of new threads to
273 * be the same as the thread invoking this
274 * <tt>privilegedThreadFactory</tt> method. A new
275 * <tt>privilegedThreadFactory</tt> can be created within an
276 * {@link AccessController#doPrivileged} action setting the
277 * current thread's access control context to create threads with
278 * the selected permission settings holding within that action.
279 *
280 * <p> Note that while tasks running within such threads will have
281 * the same access control and class loader settings as the
282 * current thread, they need not have the same {@link
283 * java.lang.ThreadLocal} or {@link
284 * java.lang.InheritableThreadLocal} values. If necessary,
285 * particular values of thread locals can be set or reset before
286 * any task runs in {@link ThreadPoolExecutor} subclasses using
287 * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
288 * necessary to initialize worker threads to have the same
289 * InheritableThreadLocal settings as some other designated
290 * thread, you can create a custom ThreadFactory in which that
291 * thread waits for and services requests to create others that
292 * will inherit its values.
293 *
294 * @return a thread factory
295 * @throws AccessControlException if the current access control
296 * context does not have permission to both get and set context
297 * class loader.
298 */
299 public static ThreadFactory privilegedThreadFactory() {
300 return new PrivilegedThreadFactory();
301 }
302
303 /**
304 * Returns a {@link Callable} object that, when
305 * called, runs the given task and returns the given result. This
306 * can be useful when applying methods requiring a
307 * <tt>Callable</tt> to an otherwise resultless action.
308 * @param task the task to run
309 * @param result the result to return
310 * @throws NullPointerException if task null
311 * @return a callable object
312 */
313 public static <T> Callable<T> callable(Runnable task, T result) {
314 if (task == null)
315 throw new NullPointerException();
316 return new RunnableAdapter<T>(task, result);
317 }
318
319 /**
320 * Returns a {@link Callable} object that, when
321 * called, runs the given task and returns <tt>null</tt>.
322 * @param task the task to run
323 * @return a callable object
324 * @throws NullPointerException if task null
325 */
326 public static Callable<Object> callable(Runnable task) {
327 if (task == null)
328 throw new NullPointerException();
329 return new RunnableAdapter<Object>(task, null);
330 }
331
332 /**
333 * Returns a {@link Callable} object that, when
334 * called, runs the given privileged action and returns its result.
335 * @param action the privileged action to run
336 * @return a callable object
337 * @throws NullPointerException if action null
338 */
339 public static Callable<Object> callable(PrivilegedAction action) {
340 if (action == null)
341 throw new NullPointerException();
342 return new PrivilegedActionAdapter(action);
343 }
344
345 /**
346 * Returns a {@link Callable} object that, when
347 * called, runs the given privileged exception action and returns
348 * its result.
349 * @param action the privileged exception action to run
350 * @return a callable object
351 * @throws NullPointerException if action null
352 */
353 public static Callable<Object> callable(PrivilegedExceptionAction action) {
354 if (action == null)
355 throw new NullPointerException();
356 return new PrivilegedExceptionActionAdapter(action);
357 }
358
359 /**
360 * Returns a {@link Callable} object that will, when
361 * called, execute the given <tt>callable</tt> under the current
362 * access control context. This method should normally be
363 * invoked within an {@link AccessController#doPrivileged} action
364 * to create callables that will, if possible, execute under the
365 * selected permission settings holding within that action; or if
366 * not possible, throw an associated {@link
367 * AccessControlException}.
368 * @param callable the underlying task
369 * @return a callable object
370 * @throws NullPointerException if callable null
371 *
372 */
373 public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
374 if (callable == null)
375 throw new NullPointerException();
376 return new PrivilegedCallable(callable);
377 }
378
379 /**
380 * Returns a {@link Callable} object that will, when
381 * called, execute the given <tt>callable</tt> under the current
382 * access control context, with the current context class loader
383 * as the context class loader. This method should normally be
384 * invoked within an {@link AccessController#doPrivileged} action
385 * to create callables that will, if possible, execute under the
386 * selected permission settings holding within that action; or if
387 * not possible, throw an associated {@link
388 * AccessControlException}.
389 * @param callable the underlying task
390 *
391 * @return a callable object
392 * @throws NullPointerException if callable null
393 * @throws AccessControlException if the current access control
394 * context does not have permission to both set and get context
395 * class loader.
396 */
397 public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
398 if (callable == null)
399 throw new NullPointerException();
400 return new PrivilegedCallableUsingCurrentClassLoader(callable);
401 }
402
403 // Non-public classes supporting the public methods
404
405 /**
406 * A callable that runs given task and returns given result
407 */
408 static final class RunnableAdapter<T> implements Callable<T> {
409 final Runnable task;
410 final T result;
411 RunnableAdapter(Runnable task, T result) {
412 this.task = task;
413 this.result = result;
414 }
415 public T call() {
416 task.run();
417 return result;
418 }
419 }
420
421 /**
422 * A callable that runs given privileged action and returns its result
423 */
424 static final class PrivilegedActionAdapter implements Callable<Object> {
425 PrivilegedActionAdapter(PrivilegedAction action) {
426 this.action = action;
427 }
428 public Object call () {
429 return action.run();
430 }
431 private final PrivilegedAction action;
432 }
433
434 /**
435 * A callable that runs given privileged exception action and returns its result
436 */
437 static final class PrivilegedExceptionActionAdapter implements Callable<Object> {
438 PrivilegedExceptionActionAdapter(PrivilegedExceptionAction action) {
439 this.action = action;
440 }
441 public Object call () throws Exception {
442 return action.run();
443 }
444 private final PrivilegedExceptionAction action;
445 }
446
447
448 /**
449 * A callable that runs under established access control settings
450 */
451 static final class PrivilegedCallable<T> implements Callable<T> {
452 private final AccessControlContext acc;
453 private final Callable<T> task;
454 private T result;
455 private Exception exception;
456 PrivilegedCallable(Callable<T> task) {
457 this.task = task;
458 this.acc = AccessController.getContext();
459 }
460
461 public T call() throws Exception {
462 AccessController.doPrivileged(new PrivilegedAction() {
463 public Object run() {
464 try {
465 result = task.call();
466 } catch(Exception ex) {
467 exception = ex;
468 }
469 return null;
470 }
471 }, acc);
472 if (exception != null)
473 throw exception;
474 else
475 return result;
476 }
477 }
478
479 /**
480 * A callable that runs under established access control settings and
481 * current ClassLoader
482 */
483 static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
484 private final ClassLoader ccl;
485 private final AccessControlContext acc;
486 private final Callable<T> task;
487 private T result;
488 private Exception exception;
489 PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
490 this.task = task;
491 this.ccl = Thread.currentThread().getContextClassLoader();
492 this.acc = AccessController.getContext();
493 acc.checkPermission(new RuntimePermission("getContextClassLoader"));
494 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
495 }
496
497 public T call() throws Exception {
498 AccessController.doPrivileged(new PrivilegedAction() {
499 public Object run() {
500 ClassLoader savedcl = null;
501 Thread t = Thread.currentThread();
502 try {
503 ClassLoader cl = t.getContextClassLoader();
504 if (ccl != cl) {
505 t.setContextClassLoader(ccl);
506 savedcl = cl;
507 }
508 result = task.call();
509 } catch(Exception ex) {
510 exception = ex;
511 } finally {
512 if (savedcl != null)
513 t.setContextClassLoader(savedcl);
514 }
515 return null;
516 }
517 }, acc);
518 if (exception != null)
519 throw exception;
520 else
521 return result;
522 }
523 }
524
525 /**
526 * The default thread factory
527 */
528 static class DefaultThreadFactory implements ThreadFactory {
529 static final AtomicInteger poolNumber = new AtomicInteger(1);
530 final ThreadGroup group;
531 final AtomicInteger threadNumber = new AtomicInteger(1);
532 final String namePrefix;
533
534 DefaultThreadFactory() {
535 SecurityManager s = System.getSecurityManager();
536 group = (s != null)? s.getThreadGroup() :
537 Thread.currentThread().getThreadGroup();
538 namePrefix = "pool-" +
539 poolNumber.getAndIncrement() +
540 "-thread-";
541 }
542
543 public Thread newThread(Runnable r) {
544 Thread t = new Thread(group, r,
545 namePrefix + threadNumber.getAndIncrement(),
546 0);
547 if (t.isDaemon())
548 t.setDaemon(false);
549 if (t.getPriority() != Thread.NORM_PRIORITY)
550 t.setPriority(Thread.NORM_PRIORITY);
551 return t;
552 }
553 }
554
555 /**
556 * Thread factory capturing access control and class loader
557 */
558 static class PrivilegedThreadFactory extends DefaultThreadFactory {
559 private final ClassLoader ccl;
560 private final AccessControlContext acc;
561
562 PrivilegedThreadFactory() {
563 super();
564 this.ccl = Thread.currentThread().getContextClassLoader();
565 this.acc = AccessController.getContext();
566 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
567 }
568
569 public Thread newThread(final Runnable r) {
570 return super.newThread(new Runnable() {
571 public void run() {
572 AccessController.doPrivileged(new PrivilegedAction() {
573 public Object run() {
574 Thread.currentThread().setContextClassLoader(ccl);
575 r.run();
576 return null;
577 }
578 }, acc);
579 }
580 });
581 }
582
583 }
584
585 /**
586 * A wrapper class that exposes only the ExecutorService methods
587 * of an implementation.
588 */
589 static class DelegatedExecutorService extends AbstractExecutorService {
590 private final ExecutorService e;
591 DelegatedExecutorService(ExecutorService executor) { e = executor; }
592 public void execute(Runnable command) { e.execute(command); }
593 public void shutdown() { e.shutdown(); }
594 public List<Runnable> shutdownNow() { return e.shutdownNow(); }
595 public boolean isShutdown() { return e.isShutdown(); }
596 public boolean isTerminated() { return e.isTerminated(); }
597 public boolean awaitTermination(long timeout, TimeUnit unit)
598 throws InterruptedException {
599 return e.awaitTermination(timeout, unit);
600 }
601 public Future<?> submit(Runnable task) {
602 return e.submit(task);
603 }
604 public <T> Future<T> submit(Callable<T> task) {
605 return e.submit(task);
606 }
607 public <T> Future<T> submit(Runnable task, T result) {
608 return e.submit(task, result);
609 }
610 public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
611 throws InterruptedException {
612 return e.invokeAll(tasks);
613 }
614 public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks,
615 long timeout, TimeUnit unit)
616 throws InterruptedException {
617 return e.invokeAll(tasks, timeout, unit);
618 }
619 public <T> T invokeAny(Collection<Callable<T>> tasks)
620 throws InterruptedException, ExecutionException {
621 return e.invokeAny(tasks);
622 }
623 public <T> T invokeAny(Collection<Callable<T>> tasks,
624 long timeout, TimeUnit unit)
625 throws InterruptedException, ExecutionException, TimeoutException {
626 return e.invokeAny(tasks, timeout, unit);
627 }
628 }
629
630 /**
631 * A wrapper class that exposes only the ExecutorService and
632 * ScheduleExecutor methods of a ScheduledExecutorService implementation.
633 */
634 static class DelegatedScheduledExecutorService
635 extends DelegatedExecutorService
636 implements ScheduledExecutorService {
637 private final ScheduledExecutorService e;
638 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
639 super(executor);
640 e = executor;
641 }
642 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
643 return e.schedule(command, delay, unit);
644 }
645 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
646 return e.schedule(callable, delay, unit);
647 }
648 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
649 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
650 }
651 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
652 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
653 }
654 }
655
656
657 /** Cannot instantiate. */
658 private Executors() {}
659 }