ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.87
Committed: Tue Jul 2 14:17:32 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.86: +1 -0 lines
Log Message:
Incorporate review suggestions

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.67 * @return a callable object
372 dl 1.42 * @throws NullPointerException if task null
373 dl 1.38 */
374     public static <T> Callable<T> callable(Runnable task, T result) {
375 dl 1.42 if (task == null)
376     throw new NullPointerException();
377 dl 1.38 return new RunnableAdapter<T>(task, result);
378     }
379    
380     /**
381 tim 1.43 * Returns a {@link Callable} object that, when
382 jsr166 1.82 * called, runs the given task and returns {@code null}.
383 dl 1.38 * @param task the task to run
384 tim 1.43 * @return a callable object
385 dl 1.42 * @throws NullPointerException if task null
386 dl 1.38 */
387     public static Callable<Object> callable(Runnable task) {
388 dl 1.42 if (task == null)
389     throw new NullPointerException();
390 dl 1.38 return new RunnableAdapter<Object>(task, null);
391     }
392    
393     /**
394 tim 1.43 * Returns a {@link Callable} object that, when
395 dl 1.49 * called, runs the given privileged action and returns its result.
396 dl 1.38 * @param action the privileged action to run
397 tim 1.43 * @return a callable object
398 dl 1.42 * @throws NullPointerException if action null
399 dl 1.38 */
400 dl 1.56 public static Callable<Object> callable(final PrivilegedAction<?> action) {
401 dl 1.42 if (action == null)
402     throw new NullPointerException();
403 dl 1.56 return new Callable<Object>() {
404 jsr166 1.69 public Object call() { return action.run(); }};
405 dl 1.38 }
406    
407     /**
408 tim 1.43 * Returns a {@link Callable} object that, when
409 dl 1.39 * called, runs the given privileged exception action and returns
410 dl 1.49 * its result.
411 dl 1.38 * @param action the privileged exception action to run
412 tim 1.43 * @return a callable object
413 dl 1.42 * @throws NullPointerException if action null
414 dl 1.38 */
415 dl 1.56 public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
416 dl 1.42 if (action == null)
417     throw new NullPointerException();
418 jsr166 1.69 return new Callable<Object>() {
419     public Object call() throws Exception { return action.run(); }};
420 dl 1.38 }
421    
422     /**
423 jsr166 1.84 * Returns a {@link Callable} object that will, when called,
424     * execute the given {@code callable} under the current access
425     * control context. This method should normally be invoked within
426     * an {@link AccessController#doPrivileged AccessController.doPrivileged}
427     * action to create callables that will, if possible, execute
428     * under the selected permission settings holding within that
429     * action; or if not possible, throw an associated {@link
430 dl 1.39 * AccessControlException}.
431     * @param callable the underlying task
432 tim 1.43 * @return a callable object
433 dl 1.42 * @throws NullPointerException if callable null
434 dl 1.39 */
435     public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
436 dl 1.42 if (callable == null)
437     throw new NullPointerException();
438 dl 1.55 return new PrivilegedCallable<T>(callable);
439 dl 1.39 }
440 jsr166 1.52
441 dl 1.39 /**
442 jsr166 1.84 * Returns a {@link Callable} object that will, when called,
443     * execute the given {@code callable} under the current access
444     * control context, with the current context class loader as the
445     * context class loader. This method should normally be invoked
446     * within an
447     * {@link AccessController#doPrivileged AccessController.doPrivileged}
448     * action to create callables that will, if possible, execute
449     * under the selected permission settings holding within that
450     * action; or if not possible, throw an associated {@link
451 dl 1.39 * AccessControlException}.
452 jsr166 1.84 *
453 dl 1.39 * @param callable the underlying task
454 tim 1.43 * @return a callable object
455 dl 1.42 * @throws NullPointerException if callable null
456 dl 1.39 * @throws AccessControlException if the current access control
457     * context does not have permission to both set and get context
458 jsr166 1.83 * class loader
459 dl 1.39 */
460     public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
461 dl 1.42 if (callable == null)
462     throw new NullPointerException();
463 dl 1.55 return new PrivilegedCallableUsingCurrentClassLoader<T>(callable);
464 dl 1.39 }
465    
466 dl 1.40 // Non-public classes supporting the public methods
467 dl 1.39
468     /**
469 dl 1.38 * A callable that runs given task and returns given result
470     */
471 dl 1.48 static final class RunnableAdapter<T> implements Callable<T> {
472     final Runnable task;
473     final T result;
474 jsr166 1.68 RunnableAdapter(Runnable task, T result) {
475 jsr166 1.52 this.task = task;
476 dl 1.38 this.result = result;
477     }
478 jsr166 1.52 public T call() {
479     task.run();
480     return result;
481 dl 1.38 }
482     }
483    
484     /**
485 dl 1.39 * A callable that runs under established access control settings
486     */
487 dl 1.48 static final class PrivilegedCallable<T> implements Callable<T> {
488 jsr166 1.68 private final Callable<T> task;
489 dl 1.39 private final AccessControlContext acc;
490 jsr166 1.68
491 jsr166 1.69 PrivilegedCallable(Callable<T> task) {
492 dl 1.39 this.task = task;
493     this.acc = AccessController.getContext();
494     }
495    
496     public T call() throws Exception {
497 jsr166 1.69 try {
498     return AccessController.doPrivileged(
499     new PrivilegedExceptionAction<T>() {
500     public T run() throws Exception {
501     return task.call();
502     }
503     }, acc);
504     } catch (PrivilegedActionException e) {
505     throw e.getException();
506     }
507 dl 1.39 }
508     }
509    
510     /**
511     * A callable that runs under established access control settings and
512     * current ClassLoader
513     */
514 dl 1.48 static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
515 jsr166 1.68 private final Callable<T> task;
516     private final AccessControlContext acc;
517 dl 1.39 private final ClassLoader ccl;
518 jsr166 1.68
519 jsr166 1.69 PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
520     SecurityManager sm = System.getSecurityManager();
521     if (sm != null) {
522     // Calls to getContextClassLoader from this class
523     // never trigger a security check, but we check
524     // whether our callers have this permission anyways.
525     sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
526    
527     // Whether setContextClassLoader turns out to be necessary
528     // or not, we fail fast if permission is not available.
529     sm.checkPermission(new RuntimePermission("setContextClassLoader"));
530     }
531 dl 1.39 this.task = task;
532 jsr166 1.68 this.acc = AccessController.getContext();
533 dl 1.39 this.ccl = Thread.currentThread().getContextClassLoader();
534     }
535    
536     public T call() throws Exception {
537 jsr166 1.69 try {
538     return AccessController.doPrivileged(
539     new PrivilegedExceptionAction<T>() {
540     public T run() throws Exception {
541     Thread t = Thread.currentThread();
542 dl 1.78 ClassLoader cl = t.getContextClassLoader();
543     if (ccl == cl) {
544     return task.call();
545     } else {
546     t.setContextClassLoader(ccl);
547     try {
548     return task.call();
549     } finally {
550     t.setContextClassLoader(cl);
551 jsr166 1.69 }
552 jsr166 1.79 }
553 jsr166 1.69 }
554     }, acc);
555     } catch (PrivilegedActionException e) {
556     throw e.getException();
557     }
558 dl 1.39 }
559     }
560    
561 dl 1.40 /**
562     * The default thread factory
563     */
564 dl 1.48 static class DefaultThreadFactory implements ThreadFactory {
565 jsr166 1.68 private static final AtomicInteger poolNumber = new AtomicInteger(1);
566     private final ThreadGroup group;
567     private final AtomicInteger threadNumber = new AtomicInteger(1);
568     private final String namePrefix;
569 dl 1.22
570 tim 1.26 DefaultThreadFactory() {
571 dl 1.22 SecurityManager s = System.getSecurityManager();
572 jsr166 1.72 group = (s != null) ? s.getThreadGroup() :
573     Thread.currentThread().getThreadGroup();
574 jsr166 1.52 namePrefix = "pool-" +
575     poolNumber.getAndIncrement() +
576 dl 1.22 "-thread-";
577     }
578    
579     public Thread newThread(Runnable r) {
580 jsr166 1.52 Thread t = new Thread(group, r,
581 dl 1.22 namePrefix + threadNumber.getAndIncrement(),
582     0);
583     if (t.isDaemon())
584     t.setDaemon(false);
585     if (t.getPriority() != Thread.NORM_PRIORITY)
586     t.setPriority(Thread.NORM_PRIORITY);
587     return t;
588     }
589     }
590    
591 dl 1.40 /**
592 jsr166 1.68 * Thread factory capturing access control context and class loader
593 dl 1.40 */
594 dl 1.48 static class PrivilegedThreadFactory extends DefaultThreadFactory {
595 jsr166 1.68 private final AccessControlContext acc;
596 dl 1.22 private final ClassLoader ccl;
597    
598     PrivilegedThreadFactory() {
599     super();
600 jsr166 1.69 SecurityManager sm = System.getSecurityManager();
601     if (sm != null) {
602     // Calls to getContextClassLoader from this class
603     // never trigger a security check, but we check
604     // whether our callers have this permission anyways.
605     sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
606    
607     // Fail fast
608     sm.checkPermission(new RuntimePermission("setContextClassLoader"));
609     }
610 jsr166 1.68 this.acc = AccessController.getContext();
611 dl 1.22 this.ccl = Thread.currentThread().getContextClassLoader();
612     }
613 jsr166 1.52
614 dl 1.22 public Thread newThread(final Runnable r) {
615     return super.newThread(new Runnable() {
616     public void run() {
617 jsr166 1.68 AccessController.doPrivileged(new PrivilegedAction<Void>() {
618     public Void run() {
619 dl 1.22 Thread.currentThread().setContextClassLoader(ccl);
620     r.run();
621 jsr166 1.52 return null;
622 dl 1.22 }
623     }, acc);
624     }
625     });
626     }
627 dl 1.36 }
628    
629 jsr166 1.58 /**
630 dl 1.36 * A wrapper class that exposes only the ExecutorService methods
631 jsr166 1.62 * of an ExecutorService implementation.
632 dl 1.36 */
633 dl 1.48 static class DelegatedExecutorService extends AbstractExecutorService {
634 dl 1.36 private final ExecutorService e;
635     DelegatedExecutorService(ExecutorService executor) { e = executor; }
636     public void execute(Runnable command) { e.execute(command); }
637     public void shutdown() { e.shutdown(); }
638     public List<Runnable> shutdownNow() { return e.shutdownNow(); }
639     public boolean isShutdown() { return e.isShutdown(); }
640     public boolean isTerminated() { return e.isTerminated(); }
641     public boolean awaitTermination(long timeout, TimeUnit unit)
642     throws InterruptedException {
643     return e.awaitTermination(timeout, unit);
644     }
645 dl 1.38 public Future<?> submit(Runnable task) {
646     return e.submit(task);
647 dl 1.36 }
648     public <T> Future<T> submit(Callable<T> task) {
649     return e.submit(task);
650     }
651 dl 1.41 public <T> Future<T> submit(Runnable task, T result) {
652     return e.submit(task, result);
653     }
654 jsr166 1.61 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
655 dl 1.36 throws InterruptedException {
656     return e.invokeAll(tasks);
657     }
658 jsr166 1.61 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
659 jsr166 1.52 long timeout, TimeUnit unit)
660 dl 1.36 throws InterruptedException {
661     return e.invokeAll(tasks, timeout, unit);
662     }
663 jsr166 1.61 public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
664 dl 1.36 throws InterruptedException, ExecutionException {
665     return e.invokeAny(tasks);
666     }
667 jsr166 1.61 public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
668 jsr166 1.52 long timeout, TimeUnit unit)
669 dl 1.36 throws InterruptedException, ExecutionException, TimeoutException {
670     return e.invokeAny(tasks, timeout, unit);
671     }
672 dl 1.66 }
673    
674     static class FinalizableDelegatedExecutorService
675 jsr166 1.69 extends DelegatedExecutorService {
676     FinalizableDelegatedExecutorService(ExecutorService executor) {
677     super(executor);
678     }
679 jsr166 1.71 protected void finalize() {
680 jsr166 1.69 super.shutdown();
681     }
682 dl 1.36 }
683 jsr166 1.52
684 dl 1.36 /**
685 jsr166 1.62 * A wrapper class that exposes only the ScheduledExecutorService
686     * methods of a ScheduledExecutorService implementation.
687 dl 1.36 */
688 dl 1.48 static class DelegatedScheduledExecutorService
689 jsr166 1.52 extends DelegatedExecutorService
690 dl 1.36 implements ScheduledExecutorService {
691     private final ScheduledExecutorService e;
692     DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
693     super(executor);
694     e = executor;
695     }
696 jsr166 1.75 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
697 dl 1.36 return e.schedule(command, delay, unit);
698     }
699     public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
700     return e.schedule(callable, delay, unit);
701     }
702 jsr166 1.75 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
703 dl 1.36 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
704     }
705 jsr166 1.75 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
706 dl 1.36 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
707     }
708 dl 1.22 }
709    
710 tim 1.15 /** Cannot instantiate. */
711     private Executors() {}
712 tim 1.1 }