ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.101
Committed: Sun Jan 21 20:18:07 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.100: +45 -12 lines
Log Message:
DelegatedExecutorService: add calls to reachabilityFence

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