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