001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.lang3.concurrent;
018
019 import java.util.concurrent.Executors;
020 import java.util.concurrent.ThreadFactory;
021 import java.util.concurrent.atomic.AtomicLong;
022
023 /**
024 * <p>
025 * An implementation of the {@code ThreadFactory} interface that provides some
026 * configuration options for the threads it creates.
027 * </p>
028 * <p>
029 * A {@code ThreadFactory} is used for instance by an {@code ExecutorService} to
030 * create the threads it uses for executing tasks. In many cases users do not
031 * have to care about a {@code ThreadFactory} because the default one used by an
032 * {@code ExecutorService} will do. However, if there are special requirements
033 * for the threads, a custom {@code ThreadFactory} has to be created.
034 * </p>
035 * <p>
036 * This class provides some frequently needed configuration options for the
037 * threads it creates. These are the following:
038 * <ul>
039 * <li>A name pattern for the threads created by this factory can be specified.
040 * This is often useful if an application uses multiple executor services for
041 * different purposes. If the names of the threads used by these services have
042 * meaningful names, log output or exception traces can be much easier to read.
043 * Naming patterns are <em>format strings</em> as used by the {@code
044 * String.format()} method. The string can contain the place holder {@code %d}
045 * which will be replaced by the number of the current thread ({@code
046 * ThreadFactoryImpl} keeps a counter of the threads it has already created).
047 * For instance, the naming pattern {@code "My %d. worker thread"} will result
048 * in thread names like {@code "My 1. worker thread"}, {@code
049 * "My 2. worker thread"} and so on.</li>
050 * <li>A flag whether the threads created by this factory should be daemon
051 * threads. This can impact the exit behavior of the current Java application
052 * because the JVM shuts down if there are only daemon threads running.</li>
053 * <li>The priority of the thread. Here an integer value can be provided. The
054 * {@code java.lang.Thread} class defines constants for valid ranges of priority
055 * values.</li>
056 * <li>The {@code UncaughtExceptionHandler} for the thread. This handler is
057 * called if an uncaught exception occurs within the thread.</li>
058 * </ul>
059 * </p>
060 * <p>
061 * {@code BasicThreadFactory} wraps another thread factory which actually
062 * creates new threads. The configuration options are set on the threads created
063 * by the wrapped thread factory. On construction time the factory to be wrapped
064 * can be specified. If none is provided, a default {@code ThreadFactory} is
065 * used.
066 * </p>
067 * <p>
068 * Instances of {@code BasicThreadFactory} are not created directly, but the
069 * nested {@code Builder} class is used for this purpose. Using the builder only
070 * the configuration options an application is interested in need to be set. The
071 * following example shows how a {@code BasicThreadFactory} is created and
072 * installed in an {@code ExecutorService}:
073 *
074 * <pre>
075 * // Create a factory that produces daemon threads with a naming pattern and
076 * // a priority
077 * BasicThreadFactory factory = new BasicThreadFactory.Builder()
078 * .namingPattern("workerthread-%d")
079 * .daemon(true)
080 * .priority(Thread.MAX_PRIORITY)
081 * .build();
082 * // Create an executor service for single-threaded execution
083 * ExecutorService exec = Executors.newSingleThreadExecutor(factory);
084 * </pre>
085 * </p>
086 *
087 * @since 3.0
088 * @version $Id: BasicThreadFactory.java 967237 2010-07-23 20:08:57Z mbenson $
089 */
090 public class BasicThreadFactory implements ThreadFactory {
091 /** A counter for the threads created by this factory. */
092 private final AtomicLong threadCounter;
093
094 /** Stores the wrapped factory. */
095 private final ThreadFactory wrappedFactory;
096
097 /** Stores the uncaught exception handler. */
098 private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
099
100 /** Stores the naming pattern for newly created threads. */
101 private final String namingPattern;
102
103 /** Stores the priority. */
104 private final Integer priority;
105
106 /** Stores the daemon status flag. */
107 private final Boolean daemonFlag;
108
109 /**
110 * Creates a new instance of {@code ThreadFactoryImpl} and configures it
111 * from the specified {@code Builder} object.
112 *
113 * @param builder the {@code Builder} object
114 */
115 private BasicThreadFactory(Builder builder) {
116 if (builder.wrappedFactory == null) {
117 wrappedFactory = Executors.defaultThreadFactory();
118 } else {
119 wrappedFactory = builder.wrappedFactory;
120 }
121
122 namingPattern = builder.namingPattern;
123 priority = builder.priority;
124 daemonFlag = builder.daemonFlag;
125 uncaughtExceptionHandler = builder.exceptionHandler;
126
127 threadCounter = new AtomicLong();
128 }
129
130 /**
131 * Returns the wrapped {@code ThreadFactory}. This factory is used for
132 * actually creating threads. This method never returns <b>null</b>. If no
133 * {@code ThreadFactory} was passed when this object was created, a default
134 * thread factory is returned.
135 *
136 * @return the wrapped {@code ThreadFactory}
137 */
138 public final ThreadFactory getWrappedFactory() {
139 return wrappedFactory;
140 }
141
142 /**
143 * Returns the naming pattern for naming newly created threads. Result can
144 * be <b>null</b> if no naming pattern was provided.
145 *
146 * @return the naming pattern
147 */
148 public final String getNamingPattern() {
149 return namingPattern;
150 }
151
152 /**
153 * Returns the daemon flag. This flag determines whether newly created
154 * threads should be daemon threads. If <b>true</b>, this factory object
155 * calls {@code setDaemon(true)} on the newly created threads. Result can be
156 * <b>null</b> if no daemon flag was provided at creation time.
157 *
158 * @return the daemon flag
159 */
160 public final Boolean getDaemonFlag() {
161 return daemonFlag;
162 }
163
164 /**
165 * Returns the priority of the threads created by this factory. Result can
166 * be <b>null</b> if no priority was specified.
167 *
168 * @return the priority for newly created threads
169 */
170 public final Integer getPriority() {
171 return priority;
172 }
173
174 /**
175 * Returns the {@code UncaughtExceptionHandler} for the threads created by
176 * this factory. Result can be <b>null</b> if no handler was provided.
177 *
178 * @return the {@code UncaughtExceptionHandler}
179 */
180 public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
181 return uncaughtExceptionHandler;
182 }
183
184 /**
185 * Returns the number of threads this factory has already created. This
186 * class maintains an internal counter that is incremented each time the
187 * {@link #newThread(Runnable)} method is invoked.
188 *
189 * @return the number of threads created by this factory
190 */
191 public long getThreadCount() {
192 return threadCounter.get();
193 }
194
195 /**
196 * Creates a new thread. This implementation delegates to the wrapped
197 * factory for creating the thread. Then, on the newly created thread the
198 * corresponding configuration options are set.
199 *
200 * @param r the {@code Runnable} to be executed by the new thread
201 * @return the newly created thread
202 */
203 public Thread newThread(Runnable r) {
204 Thread t = getWrappedFactory().newThread(r);
205 initializeThread(t);
206
207 return t;
208 }
209
210 /**
211 * Initializes the specified thread. This method is called by
212 * {@link #newThread(Runnable)} after a new thread has been obtained from
213 * the wrapped thread factory. It initializes the thread according to the
214 * options set for this factory.
215 *
216 * @param t the thread to be initialized
217 */
218 private void initializeThread(Thread t) {
219 long count = threadCounter.incrementAndGet();
220
221 if (getNamingPattern() != null) {
222 t.setName(String.format(getNamingPattern(), count));
223 }
224
225 if (getUncaughtExceptionHandler() != null) {
226 t.setUncaughtExceptionHandler(getUncaughtExceptionHandler());
227 }
228
229 if (getPriority() != null) {
230 t.setPriority(getPriority().intValue());
231 }
232
233 if (getDaemonFlag() != null) {
234 t.setDaemon(getDaemonFlag().booleanValue());
235 }
236 }
237
238 /**
239 * <p>
240 * A <em>builder</em> class for creating instances of {@code
241 * BasicThreadFactory}.
242 * </p>
243 * <p>
244 * Using this builder class instances of {@code BasicThreadFactory} can be
245 * created and initialized. The class provides methods that correspond to
246 * the configuration options supported by {@code BasicThreadFactory}. Method
247 * chaining is supported. Refer to the documentation of {@code
248 * BasicThreadFactory} for a usage example.
249 * </p>
250 *
251 * @version $Id: BasicThreadFactory.java 967237 2010-07-23 20:08:57Z mbenson $
252 */
253 public static class Builder
254 implements org.apache.commons.lang3.builder.Builder<BasicThreadFactory> {
255
256 /** The wrapped factory. */
257 private ThreadFactory wrappedFactory;
258
259 /** The uncaught exception handler. */
260 private Thread.UncaughtExceptionHandler exceptionHandler;
261
262 /** The naming pattern. */
263 private String namingPattern;
264
265 /** The priority. */
266 private Integer priority;
267
268 /** The daemon flag. */
269 private Boolean daemonFlag;
270
271 /**
272 * Sets the {@code ThreadFactory} to be wrapped by the new {@code
273 * BasicThreadFactory}.
274 *
275 * @param factory the wrapped {@code ThreadFactory} (must not be
276 * <b>null</b>)
277 * @return a reference to this {@code Builder}
278 * @throws NullPointerException if the passed in {@code ThreadFactory}
279 * is <b>null</b>
280 */
281 public Builder wrappedFactory(ThreadFactory factory) {
282 if (factory == null) {
283 throw new NullPointerException(
284 "Wrapped ThreadFactory must not be null!");
285 }
286
287 wrappedFactory = factory;
288 return this;
289 }
290
291 /**
292 * Sets the naming pattern to be used by the new {@code
293 * BasicThreadFactory}.
294 *
295 * @param pattern the naming pattern (must not be <b>null</b>)
296 * @return a reference to this {@code Builder}
297 * @throws NullPointerException if the naming pattern is <b>null</b>
298 */
299 public Builder namingPattern(String pattern) {
300 if (pattern == null) {
301 throw new NullPointerException(
302 "Naming pattern must not be null!");
303 }
304
305 namingPattern = pattern;
306 return this;
307 }
308
309 /**
310 * Sets the daemon flag for the new {@code BasicThreadFactory}. If this
311 * flag is set to <b>true</b> the new thread factory will create daemon
312 * threads.
313 *
314 * @param f the value of the daemon flag
315 * @return a reference to this {@code Builder}
316 */
317 public Builder daemon(boolean f) {
318 daemonFlag = Boolean.valueOf(f);
319 return this;
320 }
321
322 /**
323 * Sets the priority for the threads created by the new {@code
324 * BasicThreadFactory}.
325 *
326 * @param prio the priority
327 * @return a reference to this {@code Builder}
328 */
329 public Builder priority(int prio) {
330 priority = Integer.valueOf(prio);
331 return this;
332 }
333
334 /**
335 * Sets the uncaught exception handler for the threads created by the
336 * new {@code BasicThreadFactory}.
337 *
338 * @param handler the {@code UncaughtExceptionHandler} (must not be
339 * <b>null</b>)
340 * @return a reference to this {@code Builder}
341 * @throws NullPointerException if the exception handler is <b>null</b>
342 */
343 public Builder uncaughtExceptionHandler(
344 Thread.UncaughtExceptionHandler handler) {
345 if (handler == null) {
346 throw new NullPointerException(
347 "Uncaught exception handler must not be null!");
348 }
349
350 exceptionHandler = handler;
351 return this;
352 }
353
354 /**
355 * Resets this builder. All configuration options are set to default
356 * values. Note: If the {@link #build()} method was called, it is not
357 * necessary to call {@code reset()} explicitly because this is done
358 * automatically.
359 */
360 public void reset() {
361 wrappedFactory = null;
362 exceptionHandler = null;
363 namingPattern = null;
364 priority = null;
365 daemonFlag = null;
366 }
367
368 /**
369 * Creates a new {@code BasicThreadFactory} with all configuration
370 * options that have been specified by calling methods on this builder.
371 * After creating the factory {@link #reset()} is called.
372 *
373 * @return the new {@code BasicThreadFactory}
374 */
375 public BasicThreadFactory build() {
376 BasicThreadFactory factory = new BasicThreadFactory(this);
377 reset();
378 return factory;
379 }
380 }
381 }