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