ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.101
Committed: Sun Jan 21 20:18:07 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.100: +45 -12 lines
Log Message:
DelegatedExecutorService: add calls to reachabilityFence

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