ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.29
Committed: Sun Dec 7 15:00:46 2003 UTC (20 years, 6 months ago) by tim
Branch: MAIN
Changes since 1.28: +3 -6 lines
Log Message:
ScheduledExecutorService for Executors factory method return type

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain. Use, modify, and
4 * redistribute this code in any way without acknowledgement.
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
15 /**
16 * Factory and utility methods for {@link Executor}, {@link
17 * ExecutorService}, {@link ThreadFactory}, and {@link Future}
18 * classes defined in this package.
19 *
20 * @since 1.5
21 * @author Doug Lea
22 */
23 public class Executors {
24
25 /**
26 * A wrapper class that exposes only the ExecutorService methods
27 * of an implementation.
28 */
29 private static class DelegatedExecutorService implements ExecutorService {
30 private final ExecutorService e;
31 DelegatedExecutorService(ExecutorService executor) { e = executor; }
32 public void execute(Runnable command) { e.execute(command); }
33 public void shutdown() { e.shutdown(); }
34 public List shutdownNow() { return e.shutdownNow(); }
35 public boolean isShutdown() { return e.isShutdown(); }
36 public boolean isTerminated() { return e.isTerminated(); }
37 public boolean awaitTermination(long timeout, TimeUnit unit)
38 throws InterruptedException {
39 return e.awaitTermination(timeout, unit);
40 }
41 }
42
43 /**
44 * A wrapper class that exposes only the ExecutorService and
45 * ScheduleExecutor methods of a ScheduledThreadPoolExecutor.
46 */
47 private static class DelegatedScheduledExecutorService
48 extends DelegatedExecutorService
49 implements ScheduledExecutorService {
50 private final ScheduledExecutor e;
51 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
52 super(executor);
53 e = executor;
54 }
55 public ScheduledFuture<Boolean> schedule(Runnable command, long delay, TimeUnit unit) {
56 return e.schedule(command, delay, unit);
57 }
58 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
59 return e.schedule(callable, delay, unit);
60 }
61 public ScheduledFuture<Boolean> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
62 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
63 }
64 public ScheduledFuture<Boolean> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
65 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
66 }
67 }
68
69 /**
70 * Creates a thread pool that reuses a fixed set of threads
71 * operating off a shared unbounded queue. If any thread
72 * terminates due to a failure during execution prior to shutdown,
73 * a new one will take its place if needed to execute subsequent
74 * tasks.
75 *
76 * @param nThreads the number of threads in the pool
77 * @return the newly created thread pool
78 */
79 public static ExecutorService newFixedThreadPool(int nThreads) {
80 return new DelegatedExecutorService
81 (new ThreadPoolExecutor(nThreads, nThreads,
82 0L, TimeUnit.MILLISECONDS,
83 new LinkedBlockingQueue<Runnable>()));
84 }
85
86 /**
87 * Creates a thread pool that reuses a fixed set of threads
88 * operating off a shared unbounded queue, using the provided
89 * ThreadFactory to create new threads when needed.
90 *
91 * @param nThreads the number of threads in the pool
92 * @param threadFactory the factory to use when creating new threads
93 * @return the newly created thread pool
94 */
95 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
96 return new DelegatedExecutorService
97 (new ThreadPoolExecutor(nThreads, nThreads,
98 0L, TimeUnit.MILLISECONDS,
99 new LinkedBlockingQueue<Runnable>(),
100 threadFactory));
101 }
102
103 /**
104 * Creates an Executor that uses a single worker thread operating
105 * off an unbounded queue. (Note however that if this single
106 * thread terminates due to a failure during execution prior to
107 * shutdown, a new one will take its place if needed to execute
108 * subsequent tasks.) Tasks are guaranteed to execute
109 * sequentially, and no more than one task will be active at any
110 * given time. This method is equivalent in effect to
111 *<tt>new FixedThreadPool(1)</tt>.
112 *
113 * @return the newly-created single-threaded Executor
114 */
115 public static ExecutorService newSingleThreadExecutor() {
116 return new DelegatedExecutorService
117 (new ThreadPoolExecutor(1, 1,
118 0L, TimeUnit.MILLISECONDS,
119 new LinkedBlockingQueue<Runnable>()));
120 }
121
122 /**
123 * Creates an Executor that uses a single worker thread operating
124 * off an unbounded queue, and uses the provided ThreadFactory to
125 * create new threads when needed.
126 * @param threadFactory the factory to use when creating new
127 * threads
128 *
129 * @return the newly-created single-threaded Executor
130 */
131 public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
132 return new DelegatedExecutorService
133 (new ThreadPoolExecutor(1, 1,
134 0L, TimeUnit.MILLISECONDS,
135 new LinkedBlockingQueue<Runnable>(),
136 threadFactory));
137 }
138
139 /**
140 * Creates a thread pool that creates new threads as needed, but
141 * will reuse previously constructed threads when they are
142 * available. These pools will typically improve the performance
143 * of programs that execute many short-lived asynchronous tasks.
144 * Calls to <tt>execute</tt> will reuse previously constructed
145 * threads if available. If no existing thread is available, a new
146 * thread will be created and added to the pool. Threads that have
147 * not been used for sixty seconds are terminated and removed from
148 * the cache. Thus, a pool that remains idle for long enough will
149 * not consume any resources. Note that pools with similar
150 * properties but different details (for example, timeout parameters)
151 * may be created using {@link ThreadPoolExecutor} constructors.
152 *
153 * @return the newly created thread pool
154 */
155 public static ExecutorService newCachedThreadPool() {
156 return new DelegatedExecutorService
157 (new ThreadPoolExecutor(0, Integer.MAX_VALUE,
158 60, TimeUnit.SECONDS,
159 new SynchronousQueue<Runnable>()));
160 }
161
162 /**
163 * Creates a thread pool that creates new threads as needed, but
164 * will reuse previously constructed threads when they are
165 * available, and uses the provided
166 * ThreadFactory to create new threads when needed.
167 * @param threadFactory the factory to use when creating new threads
168 * @return the newly created thread pool
169 */
170 public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
171 return new DelegatedExecutorService
172 (new ThreadPoolExecutor(0, Integer.MAX_VALUE,
173 60, TimeUnit.SECONDS,
174 new SynchronousQueue<Runnable>(),
175 threadFactory));
176 }
177
178 /**
179 * Creates a thread pool that can schedule commands to run after a
180 * given delay, or to execute periodically.
181 * @return a newly created scheduled thread pool with termination management
182 */
183 public static ScheduledExecutorService newScheduledThreadPool() {
184 return newScheduledThreadPool(1);
185 }
186
187 /**
188 * Creates a thread pool that can schedule commands to run after a
189 * given delay, or to execute periodically.
190 * @param corePoolSize the number of threads to keep in the pool,
191 * even if they are idle.
192 * @return a newly created scheduled thread pool with termination management
193 */
194 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
195 return new DelegatedScheduledExecutorService
196 (new ScheduledThreadPoolExecutor(corePoolSize));
197 }
198
199 /**
200 * Creates a thread pool that can schedule commands to run after a
201 * given delay, or to execute periodically.
202 * @param corePoolSize the number of threads to keep in the pool,
203 * even if they are idle.
204 * @param threadFactory the factory to use when the executor
205 * creates a new thread.
206 * @return a newly created scheduled thread pool with termination management
207 */
208 public static ScheduledExecutorService newScheduledThreadPool(
209 int corePoolSize, ThreadFactory threadFactory) {
210 return new DelegatedScheduledExecutorService
211 (new ScheduledThreadPoolExecutor(corePoolSize, threadFactory));
212 }
213
214 /**
215 * Executes a Runnable task and returns a Future representing that
216 * task.
217 *
218 * @param executor the Executor to which the task will be submitted
219 * @param task the task to submit
220 * @return a Future representing pending completion of the task,
221 * and whose <tt>get()</tt> method will return <tt>Boolean.TRUE</tt>
222 * upon completion
223 * @throws RejectedExecutionException if task cannot be scheduled
224 * for execution
225 */
226 public static Future<Boolean> execute(Executor executor, Runnable task) {
227 FutureTask<Boolean> ftask = new FutureTask<Boolean>(task, Boolean.TRUE);
228 executor.execute(ftask);
229 return ftask;
230 }
231
232 /**
233 * Executes a Runnable task and returns a Future representing that
234 * task.
235 *
236 * @param executor the Executor to which the task will be submitted
237 * @param task the task to submit
238 * @param value the value which will become the return value of
239 * the task upon task completion
240 * @return a Future representing pending completion of the task
241 * @throws RejectedExecutionException if task cannot be scheduled
242 * for execution
243 */
244 public static <T> Future<T> execute(Executor executor, Runnable task, T value) {
245 FutureTask<T> ftask = new FutureTask<T>(task, value);
246 executor.execute(ftask);
247 return ftask;
248 }
249
250 /**
251 * Executes a value-returning task and returns a Future
252 * representing the pending results of the task.
253 *
254 * @param executor the Executor to which the task will be submitted
255 * @param task the task to submit
256 * @return a Future representing pending completion of the task
257 * @throws RejectedExecutionException if task cannot be scheduled
258 * for execution
259 */
260 public static <T> Future<T> execute(Executor executor, Callable<T> task) {
261 FutureTask<T> ftask = new FutureTask<T>(task);
262 executor.execute(ftask);
263 return ftask;
264 }
265
266 /**
267 * Executes a Runnable task and blocks until it completes normally
268 * or throws an exception.
269 *
270 * @param executor the Executor to which the task will be submitted
271 * @param task the task to submit
272 * @throws RejectedExecutionException if task cannot be scheduled
273 * for execution
274 * @throws ExecutionException if the task encountered an exception
275 * while executing
276 */
277 public static void invoke(Executor executor, Runnable task)
278 throws ExecutionException, InterruptedException {
279 FutureTask<Boolean> ftask = new FutureTask<Boolean>(task, Boolean.TRUE);
280 executor.execute(ftask);
281 ftask.get();
282 }
283
284 /**
285 * Executes a value-returning task and blocks until it returns a
286 * value or throws an exception.
287 *
288 * @param executor the Executor to which the task will be submitted
289 * @param task the task to submit
290 * @return a Future representing pending completion of the task
291 * @throws RejectedExecutionException if task cannot be scheduled
292 * for execution
293 * @throws InterruptedException if interrupted while waiting for
294 * completion
295 * @throws ExecutionException if the task encountered an exception
296 * while executing
297 */
298 public static <T> T invoke(Executor executor, Callable<T> task)
299 throws ExecutionException, InterruptedException {
300 FutureTask<T> ftask = new FutureTask<T>(task);
301 executor.execute(ftask);
302 return ftask.get();
303 }
304
305
306 /**
307 * Executes a privileged action under the current access control
308 * context and returns a Future representing the pending result
309 * object of that action.
310 *
311 * @param executor the Executor to which the task will be submitted
312 * @param action the action to submit
313 * @return a Future representing pending completion of the action
314 * @throws RejectedExecutionException if action cannot be scheduled
315 * for execution
316 */
317 public static Future<Object> execute(Executor executor, PrivilegedAction action) {
318 Callable<Object> task = new PrivilegedActionAdapter(action);
319 FutureTask<Object> future = new PrivilegedFutureTask<Object>(task);
320 executor.execute(future);
321 return future;
322 }
323
324 /**
325 * Executes a privileged exception action under the current access control
326 * context and returns a Future representing the pending result
327 * object of that action.
328 *
329 * @param executor the Executor to which the task will be submitted
330 * @param action the action to submit
331 * @return a Future representing pending completion of the action
332 * @throws RejectedExecutionException if action cannot be scheduled
333 * for execution
334 */
335 public static Future<Object> execute(Executor executor, PrivilegedExceptionAction action) {
336 Callable<Object> task = new PrivilegedExceptionActionAdapter(action);
337 FutureTask<Object> future = new PrivilegedFutureTask<Object>(task);
338 executor.execute(future);
339 return future;
340 }
341
342 private static class PrivilegedActionAdapter implements Callable<Object> {
343 PrivilegedActionAdapter(PrivilegedAction action) {
344 this.action = action;
345 }
346 public Object call () {
347 return action.run();
348 }
349 private final PrivilegedAction action;
350 }
351
352 private static class PrivilegedExceptionActionAdapter implements Callable<Object> {
353 PrivilegedExceptionActionAdapter(PrivilegedExceptionAction action) {
354 this.action = action;
355 }
356 public Object call () throws Exception {
357 return action.run();
358 }
359 private final PrivilegedExceptionAction action;
360 }
361
362 /**
363 * Return a default thread factory used to create new threads.
364 * This factory creates all new threads used by an Executor in the
365 * same {@link ThreadGroup}. If there is a {@link
366 * java.lang.SecurityManager}, it uses the group of {@link
367 * System#getSecurityManager}, else the group of the thread
368 * invoking this <tt>defaultThreadFactory</tt> method. Each new
369 * thread is created as a non-daemon thread with priority
370 * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
371 * accessible via {@link Thread#getName} of
372 * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
373 * number of this factory, and <em>M</em> is the sequence number
374 * of the thread created by this factory.
375 * @return the thread factory
376 */
377 public static ThreadFactory defaultThreadFactory() {
378 return new DefaultThreadFactory();
379 }
380
381 /**
382 * Return a thread factory used to create new threads that
383 * have the same permissions as the current thread.
384 * This factory creates threads with the same settings as {@link
385 * Executors#defaultThreadFactory}, additionally setting the
386 * AccessControlContext and contextClassLoader of new threads to
387 * be the same as the thread invoking this
388 * <tt>privilegedThreadFactory</tt> method. A new
389 * <tt>privilegedThreadFactory</tt> can be created within an
390 * {@link AccessController#doPrivileged} action setting the
391 * current thread's access control context to create threads with
392 * the selected permission settings holding within that action.
393 *
394 * <p> Note that while tasks running within such threads will have
395 * the same access control and class loader settings as the
396 * current thread, they need not have the same {@link
397 * java.lang.ThreadLocal} or {@link
398 * java.lang.InheritableThreadLocal} values. If necessary,
399 * particular values of thread locals can be set or reset before
400 * any task runs in {@link ThreadPoolExecutor} subclasses using
401 * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
402 * necessary to initialize worker threads to have the same
403 * InheritableThreadLocal settings as some other designated
404 * thread, you can create a custom ThreadFactory in which that
405 * thread waits for and services requests to create others that
406 * will inherit its values.
407 *
408 * @return the thread factory
409 * @throws AccessControlException if the current access control
410 * context does not have permission to both get and set context
411 * class loader.
412 * @see PrivilegedFutureTask
413 */
414 public static ThreadFactory privilegedThreadFactory() {
415 return new PrivilegedThreadFactory();
416 }
417
418 static class DefaultThreadFactory implements ThreadFactory {
419 static final AtomicInteger poolNumber = new AtomicInteger(1);
420 final ThreadGroup group;
421 final AtomicInteger threadNumber = new AtomicInteger(1);
422 final String namePrefix;
423
424 DefaultThreadFactory() {
425 SecurityManager s = System.getSecurityManager();
426 group = (s != null)? s.getThreadGroup() :
427 Thread.currentThread().getThreadGroup();
428 namePrefix = "pool-" +
429 poolNumber.getAndIncrement() +
430 "-thread-";
431 }
432
433 public Thread newThread(Runnable r) {
434 Thread t = new Thread(group, r,
435 namePrefix + threadNumber.getAndIncrement(),
436 0);
437 if (t.isDaemon())
438 t.setDaemon(false);
439 if (t.getPriority() != Thread.NORM_PRIORITY)
440 t.setPriority(Thread.NORM_PRIORITY);
441 return t;
442 }
443 }
444
445 static class PrivilegedThreadFactory extends DefaultThreadFactory {
446 private final ClassLoader ccl;
447 private final AccessControlContext acc;
448
449 PrivilegedThreadFactory() {
450 super();
451 this.ccl = Thread.currentThread().getContextClassLoader();
452 this.acc = AccessController.getContext();
453 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
454 }
455
456 public Thread newThread(final Runnable r) {
457 return super.newThread(new Runnable() {
458 public void run() {
459 AccessController.doPrivileged(new PrivilegedAction() {
460 public Object run() {
461 Thread.currentThread().setContextClassLoader(ccl);
462 r.run();
463 return null;
464 }
465 }, acc);
466 }
467 });
468 }
469
470 }
471
472
473 /** Cannot instantiate. */
474 private Executors() {}
475 }