1 /*
2  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
3  *
4  *
5  *
6  *
7  *
8  *
9  *
10  *
11  *
12  *
13  *
14  *
15  *
16  *
17  *
18  *
19  *
20  *
21  *
22  *
23  */

24
25 /*
26  *
27  *
28  *
29  *
30  *
31  * Written by Doug Lea with assistance from members of JCP JSR-166
32  * Expert Group and released to the public domain, as explained at
33  * http://creativecommons.org/publicdomain/zero/1.0/
34  */

35
36 package java.util.concurrent;
37 import java.util.*;
38 import java.util.concurrent.atomic.AtomicInteger;
39 import java.security.AccessControlContext;
40 import java.security.AccessController;
41 import java.security.PrivilegedAction;
42 import java.security.PrivilegedExceptionAction;
43 import java.security.PrivilegedActionException;
44 import java.security.AccessControlException;
45 import sun.security.util.SecurityConstants;
46
47 /**
48  * Factory and utility methods for {@link Executor}, {@link
49  * ExecutorService}, {@link ScheduledExecutorService}, {@link
50  * ThreadFactory}, and {@link Callable} classes defined in this
51  * package. This class supports the following kinds of methods:
52  *
53  * <ul>
54  *   <li> Methods that create and return an {@link ExecutorService}
55  *        set up with commonly useful configuration settings.
56  *   <li> Methods that create and return a {@link ScheduledExecutorService}
57  *        set up with commonly useful configuration settings.
58  *   <li> Methods that create and return a "wrapped" ExecutorService, that
59  *        disables reconfiguration by making implementation-specific methods
60  *        inaccessible.
61  *   <li> Methods that create and return a {@link ThreadFactory}
62  *        that sets newly created threads to a known state.
63  *   <li> Methods that create and return a {@link Callable}
64  *        out of other closure-like forms, so they can be used
65  *        in execution methods requiring {@code Callable}.
66  * </ul>
67  *
68  * @since 1.5
69  * @author Doug Lea
70  */

71 public class Executors {
72
73     /**
74      * Creates a thread pool that reuses a fixed number of threads
75      * operating off a shared unbounded queue.  At any point, at most
76      * {@code nThreads} threads will be active processing tasks.
77      * If additional tasks are submitted when all threads are active,
78      * they will wait in the queue until a thread is available.
79      * If any thread terminates due to a failure during execution
80      * prior to shutdown, a new one will take its place if needed to
81      * execute subsequent tasks.  The threads in the pool will exist
82      * until it is explicitly {@link ExecutorService#shutdown shutdown}.
83      *
84      * @param nThreads the number of threads in the pool
85      * @return the newly created thread pool
86      * @throws IllegalArgumentException if {@code nThreads <= 0}
87      */

88     public static ExecutorService newFixedThreadPool(int nThreads) {
89         return new ThreadPoolExecutor(nThreads, nThreads,
90                                       0L, TimeUnit.MILLISECONDS,
91                                       new LinkedBlockingQueue<Runnable>());
92     }
93
94     /**
95      * Creates a thread pool that maintains enough threads to support
96      * the given parallelism level, and may use multiple queues to
97      * reduce contention. The parallelism level corresponds to the
98      * maximum number of threads actively engaged in, or available to
99      * engage in, task processing. The actual number of threads may
100      * grow and shrink dynamically. A work-stealing pool makes no
101      * guarantees about the order in which submitted tasks are
102      * executed.
103      *
104      * @param parallelism the targeted parallelism level
105      * @return the newly created thread pool
106      * @throws IllegalArgumentException if {@code parallelism <= 0}
107      * @since 1.8
108      */

109     public static ExecutorService newWorkStealingPool(int parallelism) {
110         return new ForkJoinPool
111             (parallelism,
112              ForkJoinPool.defaultForkJoinWorkerThreadFactory,
113              nulltrue);
114     }
115
116     /**
117      * Creates a work-stealing thread pool using all
118      * {@link Runtime#availableProcessors available processors}
119      * as its target parallelism level.
120      * @return the newly created thread pool
121      * @see #newWorkStealingPool(int)
122      * @since 1.8
123      */

124     public static ExecutorService newWorkStealingPool() {
125         return new ForkJoinPool
126             (Runtime.getRuntime().availableProcessors(),
127              ForkJoinPool.defaultForkJoinWorkerThreadFactory,
128              nulltrue);
129     }
130
131     /**
132      * Creates a thread pool that reuses a fixed number of threads
133      * operating off a shared unbounded queue, using the provided
134      * ThreadFactory to create new threads when needed.  At any point,
135      * at most {@code nThreads} threads will be active processing
136      * tasks.  If additional tasks are submitted when all threads are
137      * active, they will wait in the queue until a thread is
138      * available.  If any thread terminates due to a failure during
139      * execution prior to shutdown, a new one will take its place if
140      * needed to execute subsequent tasks.  The threads in the pool will
141      * exist until it is explicitly {@link ExecutorService#shutdown
142      * shutdown}.
143      *
144      * @param nThreads the number of threads in the pool
145      * @param threadFactory the factory to use when creating new threads
146      * @return the newly created thread pool
147      * @throws NullPointerException if threadFactory is null
148      * @throws IllegalArgumentException if {@code nThreads <= 0}
149      */

150     public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
151         return new ThreadPoolExecutor(nThreads, nThreads,
152                                       0L, TimeUnit.MILLISECONDS,
153                                       new LinkedBlockingQueue<Runnable>(),
154                                       threadFactory);
155     }
156
157     /**
158      * Creates an Executor that uses a single worker thread operating
159      * off an unbounded queue. (Note however that if this single
160      * thread terminates due to a failure during execution prior to
161      * shutdown, a new one will take its place if needed to execute
162      * subsequent tasks.)  Tasks are guaranteed to execute
163      * sequentially, and no more than one task will be active at any
164      * given time. Unlike the otherwise equivalent
165      * {@code newFixedThreadPool(1)} the returned executor is
166      * guaranteed not to be reconfigurable to use additional threads.
167      *
168      * @return the newly created single-threaded Executor
169      */

170     public static ExecutorService newSingleThreadExecutor() {
171         return new FinalizableDelegatedExecutorService
172             (new ThreadPoolExecutor(1, 1,
173                                     0L, TimeUnit.MILLISECONDS,
174                                     new LinkedBlockingQueue<Runnable>()));
175     }
176
177     /**
178      * Creates an Executor that uses a single worker thread operating
179      * off an unbounded queue, and uses the provided ThreadFactory to
180      * create a new thread when needed. Unlike the otherwise
181      * equivalent {@code newFixedThreadPool(1, threadFactory)} the
182      * returned executor is guaranteed not to be reconfigurable to use
183      * additional threads.
184      *
185      * @param threadFactory the factory to use when creating new
186      * threads
187      *
188      * @return the newly created single-threaded Executor
189      * @throws NullPointerException if threadFactory is null
190      */

191     public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
192         return new FinalizableDelegatedExecutorService
193             (new ThreadPoolExecutor(1, 1,
194                                     0L, TimeUnit.MILLISECONDS,
195                                     new LinkedBlockingQueue<Runnable>(),
196                                     threadFactory));
197     }
198
199     /**
200      * Creates a thread pool that creates new threads as needed, but
201      * will reuse previously constructed threads when they are
202      * available.  These pools will typically improve the performance
203      * of programs that execute many short-lived asynchronous tasks.
204      * Calls to {@code execute} will reuse previously constructed
205      * threads if available. If no existing thread is available, a new
206      * thread will be created and added to the pool. Threads that have
207      * not been used for sixty seconds are terminated and removed from
208      * the cache. Thus, a pool that remains idle for long enough will
209      * not consume any resources. Note that pools with similar
210      * properties but different details (for example, timeout parameters)
211      * may be created using {@link ThreadPoolExecutor} constructors.
212      *
213      * @return the newly created thread pool
214      */

215     public static ExecutorService newCachedThreadPool() {
216         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
217                                       60L, TimeUnit.SECONDS,
218                                       new SynchronousQueue<Runnable>());
219     }
220
221     /**
222      * Creates a thread pool that creates new threads as needed, but
223      * will reuse previously constructed threads when they are
224      * available, and uses the provided
225      * ThreadFactory to create new threads when needed.
226      * @param threadFactory the factory to use when creating new threads
227      * @return the newly created thread pool
228      * @throws NullPointerException if threadFactory is null
229      */

230     public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
231         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
232                                       60L, TimeUnit.SECONDS,
233                                       new SynchronousQueue<Runnable>(),
234                                       threadFactory);
235     }
236
237     /**
238      * Creates a single-threaded executor that can schedule commands
239      * to run after a given delay, or to execute periodically.
240      * (Note however that if this single
241      * thread terminates due to a failure during execution prior to
242      * shutdown, a new one will take its place if needed to execute
243      * subsequent tasks.)  Tasks are guaranteed to execute
244      * sequentially, and no more than one task will be active at any
245      * given time. Unlike the otherwise equivalent
246      * {@code newScheduledThreadPool(1)} the returned executor is
247      * guaranteed not to be reconfigurable to use additional threads.
248      * @return the newly created scheduled executor
249      */

250     public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
251         return new DelegatedScheduledExecutorService
252             (new ScheduledThreadPoolExecutor(1));
253     }
254
255     /**
256      * Creates a single-threaded executor that can schedule commands
257      * to run after a given delay, or to execute periodically.  (Note
258      * however that if this single thread terminates due to a failure
259      * during execution prior to shutdown, a new one will take its
260      * place if needed to execute subsequent tasks.)  Tasks are
261      * guaranteed to execute sequentially, and no more than one task
262      * will be active at any given time. Unlike the otherwise
263      * equivalent {@code newScheduledThreadPool(1, threadFactory)}
264      * the returned executor is guaranteed not to be reconfigurable to
265      * use additional threads.
266      * @param threadFactory the factory to use when creating new
267      * threads
268      * @return a newly created scheduled executor
269      * @throws NullPointerException if threadFactory is null
270      */

271     public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
272         return new DelegatedScheduledExecutorService
273             (new ScheduledThreadPoolExecutor(1, threadFactory));
274     }
275
276     /**
277      * Creates a thread pool that can schedule commands to run after a
278      * given delay, or to execute periodically.
279      * @param corePoolSize the number of threads to keep in the pool,
280      * even if they are idle
281      * @return a newly created scheduled thread pool
282      * @throws IllegalArgumentException if {@code corePoolSize < 0}
283      */

284     public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
285         return new ScheduledThreadPoolExecutor(corePoolSize);
286     }
287
288     /**
289      * Creates a thread pool that can schedule commands to run after a
290      * given delay, or to execute periodically.
291      * @param corePoolSize the number of threads to keep in the pool,
292      * even if they are idle
293      * @param threadFactory the factory to use when the executor
294      * creates a new thread
295      * @return a newly created scheduled thread pool
296      * @throws IllegalArgumentException if {@code corePoolSize < 0}
297      * @throws NullPointerException if threadFactory is null
298      */

299     public static ScheduledExecutorService newScheduledThreadPool(
300             int corePoolSize, ThreadFactory threadFactory) {
301         return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
302     }
303
304     /**
305      * Returns an object that delegates all defined {@link
306      * ExecutorService} methods to the given executor, but not any
307      * other methods that might otherwise be accessible using
308      * casts. This provides a way to safely "freeze" configuration and
309      * disallow tuning of a given concrete implementation.
310      * @param executor the underlying implementation
311      * @return an {@code ExecutorService} instance
312      * @throws NullPointerException if executor null
313      */

314     public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
315         if (executor == null)
316             throw new NullPointerException();
317         return new DelegatedExecutorService(executor);
318     }
319
320     /**
321      * Returns an object that delegates all defined {@link
322      * ScheduledExecutorService} methods to the given executor, but
323      * not any other methods that might otherwise be accessible using
324      * casts. This provides a way to safely "freeze" configuration and
325      * disallow tuning of a given concrete implementation.
326      * @param executor the underlying implementation
327      * @return a {@code ScheduledExecutorService} instance
328      * @throws NullPointerException if executor null
329      */

330     public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
331         if (executor == null)
332             throw new NullPointerException();
333         return new DelegatedScheduledExecutorService(executor);
334     }
335
336     /**
337      * Returns a default thread factory used to create new threads.
338      * This factory creates all new threads used by an Executor in the
339      * same {@link ThreadGroup}. If there is a {@link
340      * java.lang.SecurityManager}, it uses the group of {@link
341      * System#getSecurityManager}, else the group of the thread
342      * invoking this {@code defaultThreadFactory} method. Each new
343      * thread is created as a non-daemon thread with priority set to
344      * the smaller of {@code Thread.NORM_PRIORITY} and the maximum
345      * priority permitted in the thread group.  New threads have names
346      * accessible via {@link Thread#getName} of
347      * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
348      * number of this factory, and <em>M</em> is the sequence number
349      * of the thread created by this factory.
350      * @return a thread factory
351      */

352     public static ThreadFactory defaultThreadFactory() {
353         return new DefaultThreadFactory();
354     }
355
356     /**
357      * Returns a thread factory used to create new threads that
358      * have the same permissions as the current thread.
359      * This factory creates threads with the same settings as {@link
360      * Executors#defaultThreadFactory}, additionally setting the
361      * AccessControlContext and contextClassLoader of new threads to
362      * be the same as the thread invoking this
363      * {@code privilegedThreadFactory} method.  A new
364      * {@code privilegedThreadFactory} can be created within an
365      * {@link AccessController#doPrivileged AccessController.doPrivileged}
366      * action setting the current thread's access control context to
367      * create threads with the selected permission settings holding
368      * within that action.
369      *
370      * <p>Note that while tasks running within such threads will have
371      * the same access control and class loader settings as the
372      * current thread, they need not have the same {@link
373      * java.lang.ThreadLocal} or {@link
374      * java.lang.InheritableThreadLocal} values. If necessary,
375      * particular values of thread locals can be set or reset before
376      * any task runs in {@link ThreadPoolExecutor} subclasses using
377      * {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}.
378      * Also, if it is necessary to initialize worker threads to have
379      * the same InheritableThreadLocal settings as some other
380      * designated thread, you can create a custom ThreadFactory in
381      * which that thread waits for and services requests to create
382      * others that will inherit its values.
383      *
384      * @return a thread factory
385      * @throws AccessControlException if the current access control
386      * context does not have permission to both get and set context
387      * class loader
388      */

389     public static ThreadFactory privilegedThreadFactory() {
390         return new PrivilegedThreadFactory();
391     }
392
393     /**
394      * Returns a {@link Callable} object that, when
395      * called, runs the given task and returns the given result.  This
396      * can be useful when applying methods requiring a
397      * {@code Callable} to an otherwise resultless action.
398      * @param task the task to run
399      * @param result the result to return
400      * @param <T> the type of the result
401      * @return a callable object
402      * @throws NullPointerException if task null
403      */

404     public static <T> Callable<T> callable(Runnable task, T result) {
405         if (task == null)
406             throw new NullPointerException();
407         return new RunnableAdapter<T>(task, result);
408     }
409
410     /**
411      * Returns a {@link Callable} object that, when
412      * called, runs the given task and returns {@code null}.
413      * @param task the task to run
414      * @return a callable object
415      * @throws NullPointerException if task null
416      */

417     public static Callable<Object> callable(Runnable task) {
418         if (task == null)
419             throw new NullPointerException();
420         return new RunnableAdapter<Object>(task, null);
421     }
422
423     /**
424      * Returns a {@link Callable} object that, when
425      * called, runs the given privileged action and returns its result.
426      * @param action the privileged action to run
427      * @return a callable object
428      * @throws NullPointerException if action null
429      */

430     public static Callable<Object> callable(final PrivilegedAction<?> action) {
431         if (action == null)
432             throw new NullPointerException();
433         return new Callable<Object>() {
434             public Object call() { return action.run(); }};
435     }
436
437     /**
438      * Returns a {@link Callable} object that, when
439      * called, runs the given privileged exception action and returns
440      * its result.
441      * @param action the privileged exception action to run
442      * @return a callable object
443      * @throws NullPointerException if action null
444      */

445     public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
446         if (action == null)
447             throw new NullPointerException();
448         return new Callable<Object>() {
449             public Object call() throws Exception { return action.run(); }};
450     }
451
452     /**
453      * Returns a {@link Callable} object that will, when called,
454      * execute the given {@code callable} under the current access
455      * control context. This method should normally be invoked within
456      * an {@link AccessController#doPrivileged AccessController.doPrivileged}
457      * action to create callables that will, if possible, execute
458      * under the selected permission settings holding within that
459      * action; or if not possible, throw an associated {@link
460      * AccessControlException}.
461      * @param callable the underlying task
462      * @param <T> the type of the callable's result
463      * @return a callable object
464      * @throws NullPointerException if callable null
465      */

466     public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
467         if (callable == null)
468             throw new NullPointerException();
469         return new PrivilegedCallable<T>(callable);
470     }
471
472     /**
473      * Returns a {@link Callable} object that will, when called,
474      * execute the given {@code callable} under the current access
475      * control context, with the current context class loader as the
476      * context class loader. This method should normally be invoked
477      * within an
478      * {@link AccessController#doPrivileged AccessController.doPrivileged}
479      * action to create callables that will, if possible, execute
480      * under the selected permission settings holding within that
481      * action; or if not possible, throw an associated {@link
482      * AccessControlException}.
483      *
484      * @param callable the underlying task
485      * @param <T> the type of the callable's result
486      * @return a callable object
487      * @throws NullPointerException if callable null
488      * @throws AccessControlException if the current access control
489      * context does not have permission to both set and get context
490      * class loader
491      */

492     public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
493         if (callable == null)
494             throw new NullPointerException();
495         return new PrivilegedCallableUsingCurrentClassLoader<T>(callable);
496     }
497
498     // Non-public classes supporting the public methods
499
500     /**
501      * A callable that runs given task and returns given result
502      */

503     static final class RunnableAdapter<T> implements Callable<T> {
504         final Runnable task;
505         final T result;
506         RunnableAdapter(Runnable task, T result) {
507             this.task = task;
508             this.result = result;
509         }
510         public T call() {
511             task.run();
512             return result;
513         }
514     }
515
516     /**
517      * A callable that runs under established access control settings
518      */

519     static final class PrivilegedCallable<T> implements Callable<T> {
520         private final Callable<T> task;
521         private final AccessControlContext acc;
522
523         PrivilegedCallable(Callable<T> task) {
524             this.task = task;
525             this.acc = AccessController.getContext();
526         }
527
528         public T call() throws Exception {
529             try {
530                 return AccessController.doPrivileged(
531                     new PrivilegedExceptionAction<T>() {
532                         public T run() throws Exception {
533                             return task.call();
534                         }
535                     }, acc);
536             } catch (PrivilegedActionException e) {
537                 throw e.getException();
538             }
539         }
540     }
541
542     /**
543      * A callable that runs under established access control settings and
544      * current ClassLoader
545      */

546     static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
547         private final Callable<T> task;
548         private final AccessControlContext acc;
549         private final ClassLoader ccl;
550
551         PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
552             SecurityManager sm = System.getSecurityManager();
553             if (sm != null) {
554                 // Calls to getContextClassLoader from this class
555                 // never trigger a security check, but we check
556                 // whether our callers have this permission anyways.
557                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
558
559                 // Whether setContextClassLoader turns out to be necessary
560                 // or not, we fail fast if permission is not available.
561                 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
562             }
563             this.task = task;
564             this.acc = AccessController.getContext();
565             this.ccl = Thread.currentThread().getContextClassLoader();
566         }
567
568         public T call() throws Exception {
569             try {
570                 return AccessController.doPrivileged(
571                     new PrivilegedExceptionAction<T>() {
572                         public T run() throws Exception {
573                             Thread t = Thread.currentThread();
574                             ClassLoader cl = t.getContextClassLoader();
575                             if (ccl == cl) {
576                                 return task.call();
577                             } else {
578                                 t.setContextClassLoader(ccl);
579                                 try {
580                                     return task.call();
581                                 } finally {
582                                     t.setContextClassLoader(cl);
583                                 }
584                             }
585                         }
586                     }, acc);
587             } catch (PrivilegedActionException e) {
588                 throw e.getException();
589             }
590         }
591     }
592
593     /**
594      * The default thread factory
595      */

596     static class DefaultThreadFactory implements ThreadFactory {
597         private static final AtomicInteger poolNumber = new AtomicInteger(1);
598         private final ThreadGroup group;
599         private final AtomicInteger threadNumber = new AtomicInteger(1);
600         private final String namePrefix;
601
602         DefaultThreadFactory() {
603             SecurityManager s = System.getSecurityManager();
604             group = (s != null) ? s.getThreadGroup() :
605                                   Thread.currentThread().getThreadGroup();
606             namePrefix = "pool-" +
607                           poolNumber.getAndIncrement() +
608                          "-thread-";
609         }
610
611         public Thread newThread(Runnable r) {
612             Thread t = new Thread(group, r,
613                                   namePrefix + threadNumber.getAndIncrement(),
614                                   0);
615             if (t.isDaemon())
616                 t.setDaemon(false);
617             if (t.getPriority() != Thread.NORM_PRIORITY)
618                 t.setPriority(Thread.NORM_PRIORITY);
619             return t;
620         }
621     }
622
623     /**
624      * Thread factory capturing access control context and class loader
625      */

626     static class PrivilegedThreadFactory extends DefaultThreadFactory {
627         private final AccessControlContext acc;
628         private final ClassLoader ccl;
629
630         PrivilegedThreadFactory() {
631             super();
632             SecurityManager sm = System.getSecurityManager();
633             if (sm != null) {
634                 // Calls to getContextClassLoader from this class
635                 // never trigger a security check, but we check
636                 // whether our callers have this permission anyways.
637                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
638
639                 // Fail fast
640                 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
641             }
642             this.acc = AccessController.getContext();
643             this.ccl = Thread.currentThread().getContextClassLoader();
644         }
645
646         public Thread newThread(final Runnable r) {
647             return super.newThread(new Runnable() {
648                 public void run() {
649                     AccessController.doPrivileged(new PrivilegedAction<Void>() {
650                         public Void run() {
651                             Thread.currentThread().setContextClassLoader(ccl);
652                             r.run();
653                             return null;
654                         }
655                     }, acc);
656                 }
657             });
658         }
659     }
660
661     /**
662      * A wrapper class that exposes only the ExecutorService methods
663      * of an ExecutorService implementation.
664      */

665     static class DelegatedExecutorService extends AbstractExecutorService {
666         private final ExecutorService e;
667         DelegatedExecutorService(ExecutorService executor) { e = executor; }
668         public void execute(Runnable command) { e.execute(command); }
669         public void shutdown() { e.shutdown(); }
670         public List<Runnable> shutdownNow() { return e.shutdownNow(); }
671         public boolean isShutdown() { return e.isShutdown(); }
672         public boolean isTerminated() { return e.isTerminated(); }
673         public boolean awaitTermination(long timeout, TimeUnit unit)
674             throws InterruptedException {
675             return e.awaitTermination(timeout, unit);
676         }
677         public Future<?> submit(Runnable task) {
678             return e.submit(task);
679         }
680         public <T> Future<T> submit(Callable<T> task) {
681             return e.submit(task);
682         }
683         public <T> Future<T> submit(Runnable task, T result) {
684             return e.submit(task, result);
685         }
686         public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
687             throws InterruptedException {
688             return e.invokeAll(tasks);
689         }
690         public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
691                                              long timeout, TimeUnit unit)
692             throws InterruptedException {
693             return e.invokeAll(tasks, timeout, unit);
694         }
695         public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
696             throws InterruptedException, ExecutionException {
697             return e.invokeAny(tasks);
698         }
699         public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
700                                long timeout, TimeUnit unit)
701             throws InterruptedException, ExecutionException, TimeoutException {
702             return e.invokeAny(tasks, timeout, unit);
703         }
704     }
705
706     static class FinalizableDelegatedExecutorService
707         extends DelegatedExecutorService {
708         FinalizableDelegatedExecutorService(ExecutorService executor) {
709             super(executor);
710         }
711         protected void finalize() {
712             super.shutdown();
713         }
714     }
715
716     /**
717      * A wrapper class that exposes only the ScheduledExecutorService
718      * methods of a ScheduledExecutorService implementation.
719      */

720     static class DelegatedScheduledExecutorService
721             extends DelegatedExecutorService
722             implements ScheduledExecutorService {
723         private final ScheduledExecutorService e;
724         DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
725             super(executor);
726             e = executor;
727         }
728         public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
729             return e.schedule(command, delay, unit);
730         }
731         public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
732             return e.schedule(callable, delay, unit);
733         }
734         public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
735             return e.scheduleAtFixedRate(command, initialDelay, period, unit);
736         }
737         public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
738             return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
739         }
740     }
741
742     /** Cannot instantiate. */
743     private Executors() {}
744 }
745
Powered by JavaMelody