1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.security.AccessControlContext; |
10 |
import java.security.AccessControlException; |
11 |
import java.security.AccessController; |
12 |
import java.security.PrivilegedAction; |
13 |
import java.security.PrivilegedActionException; |
14 |
import java.security.PrivilegedExceptionAction; |
15 |
import java.util.Collection; |
16 |
import java.util.List; |
17 |
import java.util.concurrent.atomic.AtomicInteger; |
18 |
import sun.security.util.SecurityConstants; |
19 |
|
20 |
/** |
21 |
* Factory and utility methods for {@link Executor}, {@link |
22 |
* ExecutorService}, {@link ScheduledExecutorService}, {@link |
23 |
* ThreadFactory}, and {@link Callable} classes defined in this |
24 |
* package. This class supports the following kinds of methods: |
25 |
* |
26 |
* <ul> |
27 |
* <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 |
* </ul> |
40 |
* |
41 |
* @since 1.5 |
42 |
* @author Doug Lea |
43 |
*/ |
44 |
public class Executors { |
45 |
|
46 |
/** |
47 |
* Creates a thread pool that reuses a fixed number of threads |
48 |
* operating off a shared unbounded queue. At any point, at most |
49 |
* {@code nThreads} threads will be active processing tasks. |
50 |
* 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 |
* |
57 |
* @param nThreads the number of threads in the pool |
58 |
* @return the newly created thread pool |
59 |
* @throws IllegalArgumentException if {@code nThreads <= 0} |
60 |
*/ |
61 |
public static ExecutorService newFixedThreadPool(int nThreads) { |
62 |
return new ThreadPoolExecutor(nThreads, nThreads, |
63 |
0L, TimeUnit.MILLISECONDS, |
64 |
new LinkedBlockingQueue<Runnable>()); |
65 |
} |
66 |
|
67 |
/** |
68 |
* 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 |
* |
77 |
* @param parallelism the targeted parallelism level |
78 |
* @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 |
ForkJoinPool.defaultForkJoinWorkerThreadFactory, |
86 |
null, true); |
87 |
} |
88 |
|
89 |
/** |
90 |
* Creates a work-stealing thread pool using all |
91 |
* {@link Runtime#availableProcessors available processors} |
92 |
* as its target parallelism level. |
93 |
* @return the newly created thread pool |
94 |
* @see #newWorkStealingPool(int) |
95 |
* @since 1.8 |
96 |
*/ |
97 |
public static ExecutorService newWorkStealingPool() { |
98 |
return new ForkJoinPool |
99 |
(Runtime.getRuntime().availableProcessors(), |
100 |
ForkJoinPool.defaultForkJoinWorkerThreadFactory, |
101 |
null, true); |
102 |
} |
103 |
|
104 |
/** |
105 |
* Creates a thread pool that reuses a fixed number of threads |
106 |
* operating off a shared unbounded queue, using the provided |
107 |
* ThreadFactory to create new threads when needed. At any point, |
108 |
* at most {@code nThreads} threads will be active processing |
109 |
* tasks. If additional tasks are submitted when all threads are |
110 |
* active, they will wait in the queue until a thread is |
111 |
* available. If any thread terminates due to a failure during |
112 |
* execution prior to shutdown, a new one will take its place if |
113 |
* needed to execute subsequent tasks. The threads in the pool will |
114 |
* exist until it is explicitly {@link ExecutorService#shutdown |
115 |
* shutdown}. |
116 |
* |
117 |
* @param nThreads the number of threads in the pool |
118 |
* @param threadFactory the factory to use when creating new threads |
119 |
* @return the newly created thread pool |
120 |
* @throws NullPointerException if threadFactory is null |
121 |
* @throws IllegalArgumentException if {@code nThreads <= 0} |
122 |
*/ |
123 |
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { |
124 |
return new ThreadPoolExecutor(nThreads, nThreads, |
125 |
0L, TimeUnit.MILLISECONDS, |
126 |
new LinkedBlockingQueue<Runnable>(), |
127 |
threadFactory); |
128 |
} |
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 |
* given time. Unlike the otherwise equivalent |
138 |
* {@code newFixedThreadPool(1)} the returned executor is |
139 |
* guaranteed not to be reconfigurable to use additional threads. |
140 |
* |
141 |
* @return the newly created single-threaded Executor |
142 |
*/ |
143 |
public static ExecutorService newSingleThreadExecutor() { |
144 |
return new FinalizableDelegatedExecutorService |
145 |
(new ThreadPoolExecutor(1, 1, |
146 |
0L, TimeUnit.MILLISECONDS, |
147 |
new LinkedBlockingQueue<Runnable>())); |
148 |
} |
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 |
* create a new thread when needed. Unlike the otherwise |
154 |
* equivalent {@code newFixedThreadPool(1, threadFactory)} the |
155 |
* returned executor is guaranteed not to be reconfigurable to use |
156 |
* additional threads. |
157 |
* |
158 |
* @param threadFactory the factory to use when creating new |
159 |
* threads |
160 |
* |
161 |
* @return the newly created single-threaded Executor |
162 |
* @throws NullPointerException if threadFactory is null |
163 |
*/ |
164 |
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { |
165 |
return new FinalizableDelegatedExecutorService |
166 |
(new ThreadPoolExecutor(1, 1, |
167 |
0L, TimeUnit.MILLISECONDS, |
168 |
new LinkedBlockingQueue<Runnable>(), |
169 |
threadFactory)); |
170 |
} |
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 |
* Calls to {@code execute} will reuse previously constructed |
178 |
* 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 |
* 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 |
* |
186 |
* @return the newly created thread pool |
187 |
*/ |
188 |
public static ExecutorService newCachedThreadPool() { |
189 |
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
190 |
60L, TimeUnit.SECONDS, |
191 |
new SynchronousQueue<Runnable>()); |
192 |
} |
193 |
|
194 |
/** |
195 |
* Creates a thread pool that creates new threads as needed, but |
196 |
* will reuse previously constructed threads when they are |
197 |
* available, and uses the provided |
198 |
* ThreadFactory to create new threads when needed. |
199 |
* @param threadFactory the factory to use when creating new threads |
200 |
* @return the newly created thread pool |
201 |
* @throws NullPointerException if threadFactory is null |
202 |
*/ |
203 |
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { |
204 |
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, |
205 |
60L, TimeUnit.SECONDS, |
206 |
new SynchronousQueue<Runnable>(), |
207 |
threadFactory); |
208 |
} |
209 |
|
210 |
/** |
211 |
* 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 |
* {@code newScheduledThreadPool(1)} the returned executor is |
220 |
* guaranteed not to be reconfigurable to use additional threads. |
221 |
* @return the newly created scheduled executor |
222 |
*/ |
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 |
* equivalent {@code newScheduledThreadPool(1, threadFactory)} |
237 |
* 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 |
* @throws NullPointerException if threadFactory is null |
243 |
*/ |
244 |
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) { |
245 |
return new DelegatedScheduledExecutorService |
246 |
(new ScheduledThreadPoolExecutor(1, threadFactory)); |
247 |
} |
248 |
|
249 |
/** |
250 |
* Creates a thread pool that can schedule commands to run after a |
251 |
* given delay, or to execute periodically. |
252 |
* @param corePoolSize the number of threads to keep in the pool, |
253 |
* even if they are idle |
254 |
* @return a newly created scheduled thread pool |
255 |
* @throws IllegalArgumentException if {@code corePoolSize < 0} |
256 |
*/ |
257 |
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { |
258 |
return new ScheduledThreadPoolExecutor(corePoolSize); |
259 |
} |
260 |
|
261 |
/** |
262 |
* Creates a thread pool that can schedule commands to run after a |
263 |
* given delay, or to execute periodically. |
264 |
* @param corePoolSize the number of threads to keep in the pool, |
265 |
* even if they are idle |
266 |
* @param threadFactory the factory to use when the executor |
267 |
* creates a new thread |
268 |
* @return a newly created scheduled thread pool |
269 |
* @throws IllegalArgumentException if {@code corePoolSize < 0} |
270 |
* @throws NullPointerException if threadFactory is null |
271 |
*/ |
272 |
public static ScheduledExecutorService newScheduledThreadPool( |
273 |
int corePoolSize, ThreadFactory threadFactory) { |
274 |
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); |
275 |
} |
276 |
|
277 |
/** |
278 |
* Returns an object that delegates all defined {@link |
279 |
* 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 |
* @return an {@code ExecutorService} instance |
285 |
* @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 |
* Returns an object that delegates all defined {@link |
295 |
* 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 |
* @return a {@code ScheduledExecutorService} instance |
301 |
* @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 |
|
309 |
/** |
310 |
* Returns a default thread factory used to create new threads. |
311 |
* 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 |
* invoking this {@code defaultThreadFactory} method. Each new |
316 |
* thread is created as a non-daemon thread with priority set to |
317 |
* the smaller of {@code Thread.NORM_PRIORITY} and the maximum |
318 |
* priority permitted in the thread group. New threads have names |
319 |
* 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 |
* @return a thread factory |
324 |
*/ |
325 |
public static ThreadFactory defaultThreadFactory() { |
326 |
return new DefaultThreadFactory(); |
327 |
} |
328 |
|
329 |
/** |
330 |
* Returns a thread factory used to create new threads that |
331 |
* have the same permissions as the current thread. |
332 |
* 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 |
* {@code privilegedThreadFactory} method. A new |
337 |
* {@code privilegedThreadFactory} can be created within an |
338 |
* {@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 |
* |
343 |
* <p>Note that while tasks running within such threads will have |
344 |
* 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 |
* {@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 |
* |
357 |
* @return a thread factory |
358 |
* @throws AccessControlException if the current access control |
359 |
* context does not have permission to both get and set context |
360 |
* class loader |
361 |
*/ |
362 |
public static ThreadFactory privilegedThreadFactory() { |
363 |
return new PrivilegedThreadFactory(); |
364 |
} |
365 |
|
366 |
/** |
367 |
* Returns a {@link Callable} object that, when |
368 |
* called, runs the given task and returns the given result. This |
369 |
* can be useful when applying methods requiring a |
370 |
* {@code Callable} to an otherwise resultless action. |
371 |
* @param task the task to run |
372 |
* @param result the result to return |
373 |
* @param <T> the type of the result |
374 |
* @return a callable object |
375 |
* @throws NullPointerException if task null |
376 |
*/ |
377 |
public static <T> Callable<T> callable(Runnable task, T result) { |
378 |
if (task == null) |
379 |
throw new NullPointerException(); |
380 |
return new RunnableAdapter<T>(task, result); |
381 |
} |
382 |
|
383 |
/** |
384 |
* Returns a {@link Callable} object that, when |
385 |
* called, runs the given task and returns {@code null}. |
386 |
* @param task the task to run |
387 |
* @return a callable object |
388 |
* @throws NullPointerException if task null |
389 |
*/ |
390 |
public static Callable<Object> callable(Runnable task) { |
391 |
if (task == null) |
392 |
throw new NullPointerException(); |
393 |
return new RunnableAdapter<Object>(task, null); |
394 |
} |
395 |
|
396 |
/** |
397 |
* Returns a {@link Callable} object that, when |
398 |
* called, runs the given privileged action and returns its result. |
399 |
* @param action the privileged action to run |
400 |
* @return a callable object |
401 |
* @throws NullPointerException if action null |
402 |
*/ |
403 |
public static Callable<Object> callable(final PrivilegedAction<?> action) { |
404 |
if (action == null) |
405 |
throw new NullPointerException(); |
406 |
return new Callable<Object>() { |
407 |
public Object call() { return action.run(); }}; |
408 |
} |
409 |
|
410 |
/** |
411 |
* Returns a {@link Callable} object that, when |
412 |
* called, runs the given privileged exception action and returns |
413 |
* its result. |
414 |
* @param action the privileged exception action to run |
415 |
* @return a callable object |
416 |
* @throws NullPointerException if action null |
417 |
*/ |
418 |
public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) { |
419 |
if (action == null) |
420 |
throw new NullPointerException(); |
421 |
return new Callable<Object>() { |
422 |
public Object call() throws Exception { return action.run(); }}; |
423 |
} |
424 |
|
425 |
/** |
426 |
* 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 |
* AccessControlException}. |
434 |
* @param callable the underlying task |
435 |
* @param <T> the type of the callable's result |
436 |
* @return a callable object |
437 |
* @throws NullPointerException if callable null |
438 |
*/ |
439 |
public static <T> Callable<T> privilegedCallable(Callable<T> callable) { |
440 |
if (callable == null) |
441 |
throw new NullPointerException(); |
442 |
return new PrivilegedCallable<T>(callable); |
443 |
} |
444 |
|
445 |
/** |
446 |
* 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 |
* AccessControlException}. |
456 |
* |
457 |
* @param callable the underlying task |
458 |
* @param <T> the type of the callable's result |
459 |
* @return a callable object |
460 |
* @throws NullPointerException if callable null |
461 |
* @throws AccessControlException if the current access control |
462 |
* context does not have permission to both set and get context |
463 |
* class loader |
464 |
*/ |
465 |
public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) { |
466 |
if (callable == null) |
467 |
throw new NullPointerException(); |
468 |
return new PrivilegedCallableUsingCurrentClassLoader<T>(callable); |
469 |
} |
470 |
|
471 |
// Non-public classes supporting the public methods |
472 |
|
473 |
/** |
474 |
* A callable that runs given task and returns given result |
475 |
*/ |
476 |
static final class RunnableAdapter<T> implements Callable<T> { |
477 |
final Runnable task; |
478 |
final T result; |
479 |
RunnableAdapter(Runnable task, T result) { |
480 |
this.task = task; |
481 |
this.result = result; |
482 |
} |
483 |
public T call() { |
484 |
task.run(); |
485 |
return result; |
486 |
} |
487 |
} |
488 |
|
489 |
/** |
490 |
* A callable that runs under established access control settings |
491 |
*/ |
492 |
static final class PrivilegedCallable<T> implements Callable<T> { |
493 |
private final Callable<T> task; |
494 |
private final AccessControlContext acc; |
495 |
|
496 |
PrivilegedCallable(Callable<T> task) { |
497 |
this.task = task; |
498 |
this.acc = AccessController.getContext(); |
499 |
} |
500 |
|
501 |
public T call() throws Exception { |
502 |
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 |
} |
513 |
} |
514 |
|
515 |
/** |
516 |
* A callable that runs under established access control settings and |
517 |
* current ClassLoader |
518 |
*/ |
519 |
static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> { |
520 |
private final Callable<T> task; |
521 |
private final AccessControlContext acc; |
522 |
private final ClassLoader ccl; |
523 |
|
524 |
PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) { |
525 |
SecurityManager sm = System.getSecurityManager(); |
526 |
if (sm != null) { |
527 |
// Calls to getContextClassLoader from this class |
528 |
// never trigger a security check, but we check |
529 |
// whether our callers have this permission anyways. |
530 |
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); |
531 |
|
532 |
// Whether setContextClassLoader turns out to be necessary |
533 |
// or not, we fail fast if permission is not available. |
534 |
sm.checkPermission(new RuntimePermission("setContextClassLoader")); |
535 |
} |
536 |
this.task = task; |
537 |
this.acc = AccessController.getContext(); |
538 |
this.ccl = Thread.currentThread().getContextClassLoader(); |
539 |
} |
540 |
|
541 |
public T call() throws Exception { |
542 |
try { |
543 |
return AccessController.doPrivileged( |
544 |
new PrivilegedExceptionAction<T>() { |
545 |
public T run() throws Exception { |
546 |
Thread t = Thread.currentThread(); |
547 |
ClassLoader cl = t.getContextClassLoader(); |
548 |
if (ccl == cl) { |
549 |
return task.call(); |
550 |
} else { |
551 |
t.setContextClassLoader(ccl); |
552 |
try { |
553 |
return task.call(); |
554 |
} finally { |
555 |
t.setContextClassLoader(cl); |
556 |
} |
557 |
} |
558 |
} |
559 |
}, acc); |
560 |
} catch (PrivilegedActionException e) { |
561 |
throw e.getException(); |
562 |
} |
563 |
} |
564 |
} |
565 |
|
566 |
/** |
567 |
* The default thread factory |
568 |
*/ |
569 |
static class DefaultThreadFactory implements ThreadFactory { |
570 |
private static final AtomicInteger poolNumber = new AtomicInteger(1); |
571 |
private final ThreadGroup group; |
572 |
private final AtomicInteger threadNumber = new AtomicInteger(1); |
573 |
private final String namePrefix; |
574 |
|
575 |
DefaultThreadFactory() { |
576 |
SecurityManager s = System.getSecurityManager(); |
577 |
group = (s != null) ? s.getThreadGroup() : |
578 |
Thread.currentThread().getThreadGroup(); |
579 |
namePrefix = "pool-" + |
580 |
poolNumber.getAndIncrement() + |
581 |
"-thread-"; |
582 |
} |
583 |
|
584 |
public Thread newThread(Runnable r) { |
585 |
Thread t = new Thread(group, r, |
586 |
namePrefix + threadNumber.getAndIncrement(), |
587 |
0); |
588 |
if (t.isDaemon()) |
589 |
t.setDaemon(false); |
590 |
if (t.getPriority() != Thread.NORM_PRIORITY) |
591 |
t.setPriority(Thread.NORM_PRIORITY); |
592 |
return t; |
593 |
} |
594 |
} |
595 |
|
596 |
/** |
597 |
* Thread factory capturing access control context and class loader |
598 |
*/ |
599 |
static class PrivilegedThreadFactory extends DefaultThreadFactory { |
600 |
private final AccessControlContext acc; |
601 |
private final ClassLoader ccl; |
602 |
|
603 |
PrivilegedThreadFactory() { |
604 |
super(); |
605 |
SecurityManager sm = System.getSecurityManager(); |
606 |
if (sm != null) { |
607 |
// Calls to getContextClassLoader from this class |
608 |
// never trigger a security check, but we check |
609 |
// whether our callers have this permission anyways. |
610 |
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); |
611 |
|
612 |
// Fail fast |
613 |
sm.checkPermission(new RuntimePermission("setContextClassLoader")); |
614 |
} |
615 |
this.acc = AccessController.getContext(); |
616 |
this.ccl = Thread.currentThread().getContextClassLoader(); |
617 |
} |
618 |
|
619 |
public Thread newThread(final Runnable r) { |
620 |
return super.newThread(new Runnable() { |
621 |
public void run() { |
622 |
AccessController.doPrivileged(new PrivilegedAction<Void>() { |
623 |
public Void run() { |
624 |
Thread.currentThread().setContextClassLoader(ccl); |
625 |
r.run(); |
626 |
return null; |
627 |
} |
628 |
}, acc); |
629 |
} |
630 |
}); |
631 |
} |
632 |
} |
633 |
|
634 |
/** |
635 |
* A wrapper class that exposes only the ExecutorService methods |
636 |
* of an ExecutorService implementation. |
637 |
*/ |
638 |
static class DelegatedExecutorService extends AbstractExecutorService { |
639 |
private final ExecutorService e; |
640 |
DelegatedExecutorService(ExecutorService executor) { e = executor; } |
641 |
public void execute(Runnable command) { e.execute(command); } |
642 |
public void shutdown() { e.shutdown(); } |
643 |
public List<Runnable> shutdownNow() { return e.shutdownNow(); } |
644 |
public boolean isShutdown() { return e.isShutdown(); } |
645 |
public boolean isTerminated() { return e.isTerminated(); } |
646 |
public boolean awaitTermination(long timeout, TimeUnit unit) |
647 |
throws InterruptedException { |
648 |
return e.awaitTermination(timeout, unit); |
649 |
} |
650 |
public Future<?> submit(Runnable task) { |
651 |
return e.submit(task); |
652 |
} |
653 |
public <T> Future<T> submit(Callable<T> task) { |
654 |
return e.submit(task); |
655 |
} |
656 |
public <T> Future<T> submit(Runnable task, T result) { |
657 |
return e.submit(task, result); |
658 |
} |
659 |
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) |
660 |
throws InterruptedException { |
661 |
return e.invokeAll(tasks); |
662 |
} |
663 |
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, |
664 |
long timeout, TimeUnit unit) |
665 |
throws InterruptedException { |
666 |
return e.invokeAll(tasks, timeout, unit); |
667 |
} |
668 |
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) |
669 |
throws InterruptedException, ExecutionException { |
670 |
return e.invokeAny(tasks); |
671 |
} |
672 |
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, |
673 |
long timeout, TimeUnit unit) |
674 |
throws InterruptedException, ExecutionException, TimeoutException { |
675 |
return e.invokeAny(tasks, timeout, unit); |
676 |
} |
677 |
} |
678 |
|
679 |
static class FinalizableDelegatedExecutorService |
680 |
extends DelegatedExecutorService { |
681 |
FinalizableDelegatedExecutorService(ExecutorService executor) { |
682 |
super(executor); |
683 |
} |
684 |
protected void finalize() { |
685 |
super.shutdown(); |
686 |
} |
687 |
} |
688 |
|
689 |
/** |
690 |
* A wrapper class that exposes only the ScheduledExecutorService |
691 |
* methods of a ScheduledExecutorService implementation. |
692 |
*/ |
693 |
static class DelegatedScheduledExecutorService |
694 |
extends DelegatedExecutorService |
695 |
implements ScheduledExecutorService { |
696 |
private final ScheduledExecutorService e; |
697 |
DelegatedScheduledExecutorService(ScheduledExecutorService executor) { |
698 |
super(executor); |
699 |
e = executor; |
700 |
} |
701 |
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { |
702 |
return e.schedule(command, delay, unit); |
703 |
} |
704 |
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { |
705 |
return e.schedule(callable, delay, unit); |
706 |
} |
707 |
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { |
708 |
return e.scheduleAtFixedRate(command, initialDelay, period, unit); |
709 |
} |
710 |
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { |
711 |
return e.scheduleWithFixedDelay(command, initialDelay, delay, unit); |
712 |
} |
713 |
} |
714 |
|
715 |
/** Cannot instantiate. */ |
716 |
private Executors() {} |
717 |
} |