ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.99
Committed: Sat Jan 20 20:44:22 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.98: +1 -1 lines
Log Message:
useless to extend AbstractExecutorService when all methods overridden

File Contents

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