ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.87
Committed: Tue Jul 2 14:17:32 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.86: +1 -0 lines
Log Message:
Incorporate review suggestions

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