ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.102
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.101: +35 -1 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

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 * @deprecated This method is only useful in conjunction with
365 * {@linkplain SecurityManager the Security Manager}, which is
366 * deprecated and subject to removal in a future release.
367 * Consequently, this method is also deprecated and subject to
368 * removal. There is no replacement for the Security Manager or this
369 * method.
370 */
371 @Deprecated(since="17", forRemoval=true)
372 public static ThreadFactory privilegedThreadFactory() {
373 return new PrivilegedThreadFactory();
374 }
375
376 /**
377 * Returns a {@link Callable} object that, when
378 * called, runs the given task and returns the given result. This
379 * can be useful when applying methods requiring a
380 * {@code Callable} to an otherwise resultless action.
381 * @param task the task to run
382 * @param result the result to return
383 * @param <T> the type of the result
384 * @return a callable object
385 * @throws NullPointerException if task null
386 */
387 public static <T> Callable<T> callable(Runnable task, T result) {
388 if (task == null)
389 throw new NullPointerException();
390 return new RunnableAdapter<T>(task, result);
391 }
392
393 /**
394 * Returns a {@link Callable} object that, when
395 * called, runs the given task and returns {@code null}.
396 * @param task the task to run
397 * @return a callable object
398 * @throws NullPointerException if task null
399 */
400 public static Callable<Object> callable(Runnable task) {
401 if (task == null)
402 throw new NullPointerException();
403 return new RunnableAdapter<Object>(task, null);
404 }
405
406 /**
407 * Returns a {@link Callable} object that, when
408 * called, runs the given privileged action and returns its result.
409 * @param action the privileged action to run
410 * @return a callable object
411 * @throws NullPointerException if action null
412 */
413 public static Callable<Object> callable(final PrivilegedAction<?> action) {
414 if (action == null)
415 throw new NullPointerException();
416 return new Callable<Object>() {
417 public Object call() { return action.run(); }};
418 }
419
420 /**
421 * Returns a {@link Callable} object that, when
422 * called, runs the given privileged exception action and returns
423 * its result.
424 * @param action the privileged exception action to run
425 * @return a callable object
426 * @throws NullPointerException if action null
427 */
428 public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
429 if (action == null)
430 throw new NullPointerException();
431 return new Callable<Object>() {
432 public Object call() throws Exception { return action.run(); }};
433 }
434
435 /**
436 * Returns a {@link Callable} object that will, when called,
437 * execute the given {@code callable} under the current access
438 * control context. This method should normally be invoked within
439 * an {@link AccessController#doPrivileged AccessController.doPrivileged}
440 * action to create callables that will, if possible, execute
441 * under the selected permission settings holding within that
442 * action; or if not possible, throw an associated {@link
443 * AccessControlException}.
444 * @param callable the underlying task
445 * @param <T> the type of the callable's result
446 * @return a callable object
447 * @throws NullPointerException if callable null
448 *
449 * @deprecated This method is only useful in conjunction with
450 * {@linkplain SecurityManager the Security Manager}, which is
451 * deprecated and subject to removal in a future release.
452 * Consequently, this method is also deprecated and subject to
453 * removal. There is no replacement for the Security Manager or this
454 * method.
455 */
456 @Deprecated(since="17", forRemoval=true)
457 public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
458 if (callable == null)
459 throw new NullPointerException();
460 return new PrivilegedCallable<T>(callable);
461 }
462
463 /**
464 * Returns a {@link Callable} object that will, when called,
465 * execute the given {@code callable} under the current access
466 * control context, with the current context class loader as the
467 * context class loader. This method should normally be invoked
468 * within an
469 * {@link AccessController#doPrivileged AccessController.doPrivileged}
470 * action to create callables that will, if possible, execute
471 * under the selected permission settings holding within that
472 * action; or if not possible, throw an associated {@link
473 * AccessControlException}.
474 *
475 * @param callable the underlying task
476 * @param <T> the type of the callable's result
477 * @return a callable object
478 * @throws NullPointerException if callable null
479 * @throws AccessControlException if the current access control
480 * context does not have permission to both set and get context
481 * class loader
482 *
483 * @deprecated This method is only useful in conjunction with
484 * {@linkplain SecurityManager the Security Manager}, which is
485 * deprecated and subject to removal in a future release.
486 * Consequently, this method is also deprecated and subject to
487 * removal. There is no replacement for the Security Manager or this
488 * method.
489 */
490 @Deprecated(since="17", forRemoval=true)
491 public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
492 if (callable == null)
493 throw new NullPointerException();
494 return new PrivilegedCallableUsingCurrentClassLoader<T>(callable);
495 }
496
497 // Non-public classes supporting the public methods
498
499 /**
500 * A callable that runs given task and returns given result.
501 */
502 private static final class RunnableAdapter<T> implements Callable<T> {
503 private final Runnable task;
504 private final T result;
505 RunnableAdapter(Runnable task, T result) {
506 this.task = task;
507 this.result = result;
508 }
509 public T call() {
510 task.run();
511 return result;
512 }
513 public String toString() {
514 return super.toString() + "[Wrapped task = " + task + "]";
515 }
516 }
517
518 /**
519 * A callable that runs under established access control settings.
520 */
521 private static final class PrivilegedCallable<T> implements Callable<T> {
522 final Callable<T> task;
523 @SuppressWarnings("removal")
524 final AccessControlContext acc;
525
526 @SuppressWarnings("removal")
527 PrivilegedCallable(Callable<T> task) {
528 this.task = task;
529 this.acc = AccessController.getContext();
530 }
531
532 @SuppressWarnings("removal")
533 public T call() throws Exception {
534 try {
535 return AccessController.doPrivileged(
536 new PrivilegedExceptionAction<T>() {
537 public T run() throws Exception {
538 return task.call();
539 }
540 }, acc);
541 } catch (PrivilegedActionException e) {
542 throw e.getException();
543 }
544 }
545
546 public String toString() {
547 return super.toString() + "[Wrapped task = " + task + "]";
548 }
549 }
550
551 /**
552 * A callable that runs under established access control settings and
553 * current ClassLoader.
554 */
555 private static final class PrivilegedCallableUsingCurrentClassLoader<T>
556 implements Callable<T> {
557 final Callable<T> task;
558 @SuppressWarnings("removal")
559 final AccessControlContext acc;
560 final ClassLoader ccl;
561
562 @SuppressWarnings("removal")
563 PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
564 SecurityManager sm = System.getSecurityManager();
565 if (sm != null) {
566 // Calls to getContextClassLoader from this class
567 // never trigger a security check, but we check
568 // whether our callers have this permission anyways.
569 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
570
571 // Whether setContextClassLoader turns out to be necessary
572 // or not, we fail fast if permission is not available.
573 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
574 }
575 this.task = task;
576 this.acc = AccessController.getContext();
577 this.ccl = Thread.currentThread().getContextClassLoader();
578 }
579
580 @SuppressWarnings("removal")
581 public T call() throws Exception {
582 try {
583 return AccessController.doPrivileged(
584 new PrivilegedExceptionAction<T>() {
585 public T run() throws Exception {
586 Thread t = Thread.currentThread();
587 ClassLoader cl = t.getContextClassLoader();
588 if (ccl == cl) {
589 return task.call();
590 } else {
591 t.setContextClassLoader(ccl);
592 try {
593 return task.call();
594 } finally {
595 t.setContextClassLoader(cl);
596 }
597 }
598 }
599 }, acc);
600 } catch (PrivilegedActionException e) {
601 throw e.getException();
602 }
603 }
604
605 public String toString() {
606 return super.toString() + "[Wrapped task = " + task + "]";
607 }
608 }
609
610 /**
611 * The default thread factory.
612 */
613 private static class DefaultThreadFactory implements ThreadFactory {
614 private static final AtomicInteger poolNumber = new AtomicInteger(1);
615 private final ThreadGroup group;
616 private final AtomicInteger threadNumber = new AtomicInteger(1);
617 private final String namePrefix;
618
619 DefaultThreadFactory() {
620 @SuppressWarnings("removal")
621 SecurityManager s = System.getSecurityManager();
622 group = (s != null) ? s.getThreadGroup() :
623 Thread.currentThread().getThreadGroup();
624 namePrefix = "pool-" +
625 poolNumber.getAndIncrement() +
626 "-thread-";
627 }
628
629 public Thread newThread(Runnable r) {
630 Thread t = new Thread(group, r,
631 namePrefix + threadNumber.getAndIncrement(),
632 0);
633 if (t.isDaemon())
634 t.setDaemon(false);
635 if (t.getPriority() != Thread.NORM_PRIORITY)
636 t.setPriority(Thread.NORM_PRIORITY);
637 return t;
638 }
639 }
640
641 /**
642 * Thread factory capturing access control context and class loader.
643 */
644 private static class PrivilegedThreadFactory extends DefaultThreadFactory {
645 @SuppressWarnings("removal")
646 final AccessControlContext acc;
647 final ClassLoader ccl;
648
649 @SuppressWarnings("removal")
650 PrivilegedThreadFactory() {
651 super();
652 SecurityManager sm = System.getSecurityManager();
653 if (sm != null) {
654 // Calls to getContextClassLoader from this class
655 // never trigger a security check, but we check
656 // whether our callers have this permission anyways.
657 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
658
659 // Fail fast
660 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
661 }
662 this.acc = AccessController.getContext();
663 this.ccl = Thread.currentThread().getContextClassLoader();
664 }
665
666 public Thread newThread(final Runnable r) {
667 return super.newThread(new Runnable() {
668 @SuppressWarnings("removal")
669 public void run() {
670 AccessController.doPrivileged(new PrivilegedAction<>() {
671 public Void run() {
672 Thread.currentThread().setContextClassLoader(ccl);
673 r.run();
674 return null;
675 }
676 }, acc);
677 }
678 });
679 }
680 }
681
682 /**
683 * A wrapper class that exposes only the ExecutorService methods
684 * of an ExecutorService implementation.
685 */
686 private static class DelegatedExecutorService
687 implements ExecutorService {
688 private final ExecutorService e;
689 DelegatedExecutorService(ExecutorService executor) { e = executor; }
690 public void execute(Runnable command) {
691 try {
692 e.execute(command);
693 } finally { reachabilityFence(this); }
694 }
695 public void shutdown() { e.shutdown(); }
696 public List<Runnable> shutdownNow() {
697 try {
698 return e.shutdownNow();
699 } finally { reachabilityFence(this); }
700 }
701 public boolean isShutdown() {
702 try {
703 return e.isShutdown();
704 } finally { reachabilityFence(this); }
705 }
706 public boolean isTerminated() {
707 try {
708 return e.isTerminated();
709 } finally { reachabilityFence(this); }
710 }
711 public boolean awaitTermination(long timeout, TimeUnit unit)
712 throws InterruptedException {
713 try {
714 return e.awaitTermination(timeout, unit);
715 } finally { reachabilityFence(this); }
716 }
717 public Future<?> submit(Runnable task) {
718 try {
719 return e.submit(task);
720 } finally { reachabilityFence(this); }
721 }
722 public <T> Future<T> submit(Callable<T> task) {
723 try {
724 return e.submit(task);
725 } finally { reachabilityFence(this); }
726 }
727 public <T> Future<T> submit(Runnable task, T result) {
728 try {
729 return e.submit(task, result);
730 } finally { reachabilityFence(this); }
731 }
732 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
733 throws InterruptedException {
734 try {
735 return e.invokeAll(tasks);
736 } finally { reachabilityFence(this); }
737 }
738 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
739 long timeout, TimeUnit unit)
740 throws InterruptedException {
741 try {
742 return e.invokeAll(tasks, timeout, unit);
743 } finally { reachabilityFence(this); }
744 }
745 public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
746 throws InterruptedException, ExecutionException {
747 try {
748 return e.invokeAny(tasks);
749 } finally { reachabilityFence(this); }
750 }
751 public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
752 long timeout, TimeUnit unit)
753 throws InterruptedException, ExecutionException, TimeoutException {
754 try {
755 return e.invokeAny(tasks, timeout, unit);
756 } finally { reachabilityFence(this); }
757 }
758 }
759
760 private static class FinalizableDelegatedExecutorService
761 extends DelegatedExecutorService {
762 FinalizableDelegatedExecutorService(ExecutorService executor) {
763 super(executor);
764 }
765 @SuppressWarnings({"deprecation", "removal"})
766 protected void finalize() {
767 super.shutdown();
768 }
769 }
770
771 /**
772 * A wrapper class that exposes only the ScheduledExecutorService
773 * methods of a ScheduledExecutorService implementation.
774 */
775 private static class DelegatedScheduledExecutorService
776 extends DelegatedExecutorService
777 implements ScheduledExecutorService {
778 private final ScheduledExecutorService e;
779 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
780 super(executor);
781 e = executor;
782 }
783 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
784 return e.schedule(command, delay, unit);
785 }
786 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
787 return e.schedule(callable, delay, unit);
788 }
789 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
790 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
791 }
792 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
793 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
794 }
795 }
796
797 /** Cannot instantiate. */
798 private Executors() {}
799 }