ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Executors.java
Revision: 1.32
Committed: Wed Dec 10 01:51:11 2003 UTC (20 years, 5 months ago) by tim
Branch: MAIN
CVS Tags: JSR166_DEC9_POST_ES_SUBMIT
Changes since 1.31: +2 -132 lines
Log Message:
Move and rename static Executors.execute/invoke to ExecutorService.submit/invoke,
providing implementations in AbstractExecutorService (which TPE extends).

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 extends AbstractExecutorService {
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 ScheduledExecutorService e;
51 DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
52 super(executor);
53 e = executor;
54 }
55 public ScheduledFuture<?> 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<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
62 return e.scheduleAtFixedRate(command, initialDelay, period, unit);
63 }
64 public ScheduledFuture<?> 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 * Return a default thread factory used to create new threads.
216 * This factory creates all new threads used by an Executor in the
217 * same {@link ThreadGroup}. If there is a {@link
218 * java.lang.SecurityManager}, it uses the group of {@link
219 * System#getSecurityManager}, else the group of the thread
220 * invoking this <tt>defaultThreadFactory</tt> method. Each new
221 * thread is created as a non-daemon thread with priority
222 * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
223 * accessible via {@link Thread#getName} of
224 * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
225 * number of this factory, and <em>M</em> is the sequence number
226 * of the thread created by this factory.
227 * @return the thread factory
228 */
229 public static ThreadFactory defaultThreadFactory() {
230 return new DefaultThreadFactory();
231 }
232
233 /**
234 * Return a thread factory used to create new threads that
235 * have the same permissions as the current thread.
236 * This factory creates threads with the same settings as {@link
237 * Executors#defaultThreadFactory}, additionally setting the
238 * AccessControlContext and contextClassLoader of new threads to
239 * be the same as the thread invoking this
240 * <tt>privilegedThreadFactory</tt> method. A new
241 * <tt>privilegedThreadFactory</tt> can be created within an
242 * {@link AccessController#doPrivileged} action setting the
243 * current thread's access control context to create threads with
244 * the selected permission settings holding within that action.
245 *
246 * <p> Note that while tasks running within such threads will have
247 * the same access control and class loader settings as the
248 * current thread, they need not have the same {@link
249 * java.lang.ThreadLocal} or {@link
250 * java.lang.InheritableThreadLocal} values. If necessary,
251 * particular values of thread locals can be set or reset before
252 * any task runs in {@link ThreadPoolExecutor} subclasses using
253 * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
254 * necessary to initialize worker threads to have the same
255 * InheritableThreadLocal settings as some other designated
256 * thread, you can create a custom ThreadFactory in which that
257 * thread waits for and services requests to create others that
258 * will inherit its values.
259 *
260 * @return the thread factory
261 * @throws AccessControlException if the current access control
262 * context does not have permission to both get and set context
263 * class loader.
264 * @see PrivilegedFutureTask
265 */
266 public static ThreadFactory privilegedThreadFactory() {
267 return new PrivilegedThreadFactory();
268 }
269
270 static class DefaultThreadFactory implements ThreadFactory {
271 static final AtomicInteger poolNumber = new AtomicInteger(1);
272 final ThreadGroup group;
273 final AtomicInteger threadNumber = new AtomicInteger(1);
274 final String namePrefix;
275
276 DefaultThreadFactory() {
277 SecurityManager s = System.getSecurityManager();
278 group = (s != null)? s.getThreadGroup() :
279 Thread.currentThread().getThreadGroup();
280 namePrefix = "pool-" +
281 poolNumber.getAndIncrement() +
282 "-thread-";
283 }
284
285 public Thread newThread(Runnable r) {
286 Thread t = new Thread(group, r,
287 namePrefix + threadNumber.getAndIncrement(),
288 0);
289 if (t.isDaemon())
290 t.setDaemon(false);
291 if (t.getPriority() != Thread.NORM_PRIORITY)
292 t.setPriority(Thread.NORM_PRIORITY);
293 return t;
294 }
295 }
296
297 static class PrivilegedThreadFactory extends DefaultThreadFactory {
298 private final ClassLoader ccl;
299 private final AccessControlContext acc;
300
301 PrivilegedThreadFactory() {
302 super();
303 this.ccl = Thread.currentThread().getContextClassLoader();
304 this.acc = AccessController.getContext();
305 acc.checkPermission(new RuntimePermission("setContextClassLoader"));
306 }
307
308 public Thread newThread(final Runnable r) {
309 return super.newThread(new Runnable() {
310 public void run() {
311 AccessController.doPrivileged(new PrivilegedAction() {
312 public Object run() {
313 Thread.currentThread().setContextClassLoader(ccl);
314 r.run();
315 return null;
316 }
317 }, acc);
318 }
319 });
320 }
321
322 }
323
324
325 /** Cannot instantiate. */
326 private Executors() {}
327 }