ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.71
Committed: Sat Oct 16 16:48:01 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.70: +1 -1 lines
Log Message:
whitespace

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