ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.84
Committed: Mon Feb 11 07:59:02 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.83: +21 -19 lines
Log Message:
javadoc link readability

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