• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package org.apache.commons.lang3.concurrent;
18 
19 import java.lang.Thread.UncaughtExceptionHandler;
20 import java.util.Objects;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23 import java.util.concurrent.ThreadFactory;
24 import java.util.concurrent.atomic.AtomicLong;
25 
26 /**
27  * An implementation of the {@link ThreadFactory} interface that provides some
28  * configuration options for the threads it creates.
29  *
30  * <p>
31  * A {@link ThreadFactory} is used for instance by an {@link ExecutorService} to
32  * create the threads it uses for executing tasks. In many cases users do not
33  * have to care about a {@link ThreadFactory} because the default one used by an
34  * {@link ExecutorService} will do. However, if there are special requirements
35  * for the threads, a custom {@link ThreadFactory} has to be created.
36  * </p>
37  * <p>
38  * This class provides some frequently needed configuration options for the
39  * threads it creates. These are the following:
40  * </p>
41  * <ul>
42  * <li>A name pattern for the threads created by this factory can be specified.
43  * This is often useful if an application uses multiple executor services for
44  * different purposes. If the names of the threads used by these services have
45  * meaningful names, log output or exception traces can be much easier to read.
46  * Naming patterns are <em>format strings</em> as used by the {@code
47  * String.format()} method. The string can contain the place holder {@code %d}
48  * which will be replaced by the number of the current thread ({@code
49  * ThreadFactoryImpl} keeps a counter of the threads it has already created).
50  * For instance, the naming pattern {@code "My %d. worker thread"} will result
51  * in thread names like {@code "My 1. worker thread"}, {@code
52  * "My 2. worker thread"} and so on.</li>
53  * <li>A flag whether the threads created by this factory should be daemon
54  * threads. This can impact the exit behavior of the current Java application
55  * because the JVM shuts down if there are only daemon threads running.</li>
56  * <li>The priority of the thread. Here an integer value can be provided. The
57  * {@code java.lang.Thread} class defines constants for valid ranges of priority
58  * values.</li>
59  * <li>The {@link UncaughtExceptionHandler} for the thread. This handler is
60  * called if an uncaught exception occurs within the thread.</li>
61  * </ul>
62  * <p>
63  * {@link BasicThreadFactory} wraps another thread factory which actually
64  * creates new threads. The configuration options are set on the threads created
65  * by the wrapped thread factory. On construction time the factory to be wrapped
66  * can be specified. If none is provided, a default {@link ThreadFactory} is
67  * used.
68  * </p>
69  * <p>
70  * Instances of {@link BasicThreadFactory} are not created directly, but the
71  * nested {@link Builder} class is used for this purpose. Using the builder only
72  * the configuration options an application is interested in need to be set. The
73  * following example shows how a {@link BasicThreadFactory} is created and
74  * installed in an {@link ExecutorService}:
75  * </p>
76  *
77  * <pre>
78  * // Create a factory that produces daemon threads with a naming pattern and
79  * // a priority
80  * BasicThreadFactory factory = new BasicThreadFactory.Builder()
81  *     .namingPattern(&quot;workerthread-%d&quot;)
82  *     .daemon(true)
83  *     .priority(Thread.MAX_PRIORITY)
84  *     .build();
85  * // Create an executor service for single-threaded execution
86  * ExecutorService exec = Executors.newSingleThreadExecutor(factory);
87  * </pre>
88  *
89  * @since 3.0
90  */
91 public class BasicThreadFactory implements ThreadFactory {
92     /** A counter for the threads created by this factory. */
93     private final AtomicLong threadCounter;
94 
95     /** Stores the wrapped factory. */
96     private final ThreadFactory wrappedFactory;
97 
98     /** Stores the uncaught exception handler. */
99     private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
100 
101     /** Stores the naming pattern for newly created threads. */
102     private final String namingPattern;
103 
104     /** Stores the priority. */
105     private final Integer priority;
106 
107     /** Stores the daemon status flag. */
108     private final Boolean daemon;
109 
110     /**
111      * Creates a new instance of {@link ThreadFactory} and configures it
112      * from the specified {@link Builder} object.
113      *
114      * @param builder the {@link Builder} object
115      */
BasicThreadFactory(final Builder builder)116     private BasicThreadFactory(final Builder builder) {
117         if (builder.wrappedFactory == null) {
118             wrappedFactory = Executors.defaultThreadFactory();
119         } else {
120             wrappedFactory = builder.wrappedFactory;
121         }
122 
123         namingPattern = builder.namingPattern;
124         priority = builder.priority;
125         daemon = builder.daemon;
126         uncaughtExceptionHandler = builder.exceptionHandler;
127 
128         threadCounter = new AtomicLong();
129     }
130 
131     /**
132      * Returns the wrapped {@link ThreadFactory}. This factory is used for
133      * actually creating threads. This method never returns <b>null</b>. If no
134      * {@link ThreadFactory} was passed when this object was created, a default
135      * thread factory is returned.
136      *
137      * @return the wrapped {@link ThreadFactory}
138      */
getWrappedFactory()139     public final ThreadFactory getWrappedFactory() {
140         return wrappedFactory;
141     }
142 
143     /**
144      * Returns the naming pattern for naming newly created threads. Result can
145      * be <b>null</b> if no naming pattern was provided.
146      *
147      * @return the naming pattern
148      */
getNamingPattern()149     public final String getNamingPattern() {
150         return namingPattern;
151     }
152 
153     /**
154      * Returns the daemon flag. This flag determines whether newly created
155      * threads should be daemon threads. If <b>true</b>, this factory object
156      * calls {@code setDaemon(true)} on the newly created threads. Result can be
157      * <b>null</b> if no daemon flag was provided at creation time.
158      *
159      * @return the daemon flag
160      */
getDaemonFlag()161     public final Boolean getDaemonFlag() {
162         return daemon;
163     }
164 
165     /**
166      * Returns the priority of the threads created by this factory. Result can
167      * be <b>null</b> if no priority was specified.
168      *
169      * @return the priority for newly created threads
170      */
getPriority()171     public final Integer getPriority() {
172         return priority;
173     }
174 
175     /**
176      * Returns the {@link UncaughtExceptionHandler} for the threads created by
177      * this factory. Result can be <b>null</b> if no handler was provided.
178      *
179      * @return the {@link UncaughtExceptionHandler}
180      */
getUncaughtExceptionHandler()181     public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
182         return uncaughtExceptionHandler;
183     }
184 
185     /**
186      * Returns the number of threads this factory has already created. This
187      * class maintains an internal counter that is incremented each time the
188      * {@link #newThread(Runnable)} method is invoked.
189      *
190      * @return the number of threads created by this factory
191      */
getThreadCount()192     public long getThreadCount() {
193         return threadCounter.get();
194     }
195 
196     /**
197      * Creates a new thread. This implementation delegates to the wrapped
198      * factory for creating the thread. Then, on the newly created thread the
199      * corresponding configuration options are set.
200      *
201      * @param runnable the {@link Runnable} to be executed by the new thread
202      * @return the newly created thread
203      */
204     @Override
newThread(final Runnable runnable)205     public Thread newThread(final Runnable runnable) {
206         final Thread thread = getWrappedFactory().newThread(runnable);
207         initializeThread(thread);
208 
209         return thread;
210     }
211 
212     /**
213      * Initializes the specified thread. This method is called by
214      * {@link #newThread(Runnable)} after a new thread has been obtained from
215      * the wrapped thread factory. It initializes the thread according to the
216      * options set for this factory.
217      *
218      * @param thread the thread to be initialized
219      */
initializeThread(final Thread thread)220     private void initializeThread(final Thread thread) {
221 
222         if (getNamingPattern() != null) {
223             final Long count = Long.valueOf(threadCounter.incrementAndGet());
224             thread.setName(String.format(getNamingPattern(), count));
225         }
226 
227         if (getUncaughtExceptionHandler() != null) {
228             thread.setUncaughtExceptionHandler(getUncaughtExceptionHandler());
229         }
230 
231         if (getPriority() != null) {
232             thread.setPriority(getPriority().intValue());
233         }
234 
235         if (getDaemonFlag() != null) {
236             thread.setDaemon(getDaemonFlag().booleanValue());
237         }
238     }
239 
240     /**
241      * A <em>builder</em> class for creating instances of {@code
242      * BasicThreadFactory}.
243      *
244      * <p>
245      * Using this builder class instances of {@link BasicThreadFactory} can be
246      * created and initialized. The class provides methods that correspond to
247      * the configuration options supported by {@link BasicThreadFactory}. Method
248      * chaining is supported. Refer to the documentation of {@code
249      * BasicThreadFactory} for a usage example.
250      * </p>
251      *
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 daemon;
270 
271         /**
272          * Sets the {@link ThreadFactory} to be wrapped by the new {@code
273          * BasicThreadFactory}.
274          *
275          * @param factory the wrapped {@link ThreadFactory} (must not be
276          * <b>null</b>)
277          * @return a reference to this {@link Builder}
278          * @throws NullPointerException if the passed in {@link ThreadFactory}
279          * is <b>null</b>
280          */
wrappedFactory(final ThreadFactory factory)281         public Builder wrappedFactory(final ThreadFactory factory) {
282             Objects.requireNonNull(factory, "factory");
283 
284             wrappedFactory = factory;
285             return this;
286         }
287 
288         /**
289          * Sets the naming pattern to be used by the new {@code
290          * BasicThreadFactory}.
291          *
292          * @param pattern the naming pattern (must not be <b>null</b>)
293          * @return a reference to this {@link Builder}
294          * @throws NullPointerException if the naming pattern is <b>null</b>
295          */
namingPattern(final String pattern)296         public Builder namingPattern(final String pattern) {
297             Objects.requireNonNull(pattern, "pattern");
298 
299             namingPattern = pattern;
300             return this;
301         }
302 
303         /**
304          * Sets the daemon flag for the new {@link BasicThreadFactory}. If this
305          * flag is set to <b>true</b> the new thread factory will create daemon
306          * threads.
307          *
308          * @param daemon the value of the daemon flag
309          * @return a reference to this {@link Builder}
310          */
daemon(final boolean daemon)311         public Builder daemon(final boolean daemon) {
312             this.daemon = Boolean.valueOf(daemon);
313             return this;
314         }
315 
316         /**
317          * Sets the priority for the threads created by the new {@code
318          * BasicThreadFactory}.
319          *
320          * @param priority the priority
321          * @return a reference to this {@link Builder}
322          */
priority(final int priority)323         public Builder priority(final int priority) {
324             this.priority = Integer.valueOf(priority);
325             return this;
326         }
327 
328         /**
329          * Sets the uncaught exception handler for the threads created by the
330          * new {@link BasicThreadFactory}.
331          *
332          * @param handler the {@link UncaughtExceptionHandler} (must not be
333          * <b>null</b>)
334          * @return a reference to this {@link Builder}
335          * @throws NullPointerException if the exception handler is <b>null</b>
336          */
uncaughtExceptionHandler( final Thread.UncaughtExceptionHandler handler)337         public Builder uncaughtExceptionHandler(
338                 final Thread.UncaughtExceptionHandler handler) {
339             Objects.requireNonNull(handler, "handler");
340 
341             exceptionHandler = handler;
342             return this;
343         }
344 
345         /**
346          * Resets this builder. All configuration options are set to default
347          * values. Note: If the {@link #build()} method was called, it is not
348          * necessary to call {@code reset()} explicitly because this is done
349          * automatically.
350          */
reset()351         public void reset() {
352             wrappedFactory = null;
353             exceptionHandler = null;
354             namingPattern = null;
355             priority = null;
356             daemon = null;
357         }
358 
359         /**
360          * Creates a new {@link BasicThreadFactory} with all configuration
361          * options that have been specified by calling methods on this builder.
362          * After creating the factory {@link #reset()} is called.
363          *
364          * @return the new {@link BasicThreadFactory}
365          */
366         @Override
build()367         public BasicThreadFactory build() {
368             final BasicThreadFactory factory = new BasicThreadFactory(this);
369             reset();
370             return factory;
371         }
372     }
373 }
374