ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.61
Committed: Thu Aug 25 19:28:17 2005 UTC (18 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +4 -4 lines
Log Message:
6267833: Incorrect method signature ExecutorService.invokeAll()

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