ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.102
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.101: +35 -1 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

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