ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.92
Committed: Sun Sep 20 02:06:19 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.91: +18 -16 lines
Log Message:
make all nested static classes private; eliminate bridge methods by making selected fields package-private

File Contents

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