ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.88
Committed: Thu Jul 18 17:13:42 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.87: +3 -0 lines
Log Message:
doclint warning fixes

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