• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.util.concurrent;
18 
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 
22 import java.lang.Thread.UncaughtExceptionHandler;
23 import java.util.concurrent.Executors;
24 import java.util.concurrent.ThreadFactory;
25 import java.util.concurrent.atomic.AtomicLong;
26 
27 /**
28  * A ThreadFactory builder, providing any combination of these features:
29  * <ul>
30  * <li> whether threads should be marked as {@linkplain Thread#setDaemon daemon}
31  * threads
32  * <li> a {@linkplain ThreadFactoryBuilder#setNameFormat naming format}
33  * <li> a {@linkplain Thread#setPriority thread priority}
34  * <li> an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception
35  * handler}
36  * <li> a {@linkplain ThreadFactory#newThread backing thread factory}
37  * </ul>
38  * If no backing thread factory is provided, a default backing thread factory is
39  * used as if by calling {@code setThreadFactory(}{@link
40  * Executors#defaultThreadFactory()}{@code )}.
41  *
42  * @author Kurt Alfred Kluever
43  * @since 4.0
44  */
45 public final class ThreadFactoryBuilder {
46   private String nameFormat = null;
47   private Boolean daemon = null;
48   private Integer priority = null;
49   private UncaughtExceptionHandler uncaughtExceptionHandler = null;
50   private ThreadFactory backingThreadFactory = null;
51 
52   /**
53    * Creates a new {@link ThreadFactory} builder.
54    */
ThreadFactoryBuilder()55   public ThreadFactoryBuilder() {}
56 
57   /**
58    * Sets the naming format to use when naming threads ({@link Thread#setName})
59    * which are created with this ThreadFactory.
60    *
61    * @param nameFormat a {@link String#format(String, Object...)}-compatible
62    *     format String, to which a unique integer (0, 1, etc.) will be supplied
63    *     as the single parameter. This integer will be unique to the built
64    *     instance of the ThreadFactory and will be assigned sequentially.
65    * @return this for the builder pattern
66    */
setNameFormat(String nameFormat)67   public ThreadFactoryBuilder setNameFormat(String nameFormat) {
68     String.format(nameFormat, 0); // fail fast if the format is bad or null
69     this.nameFormat = nameFormat;
70     return this;
71   }
72 
73   /**
74    * Sets daemon or not for new threads created with this ThreadFactory.
75    *
76    * @param daemon whether or not new Threads created with this ThreadFactory
77    *     will be daemon threads
78    * @return this for the builder pattern
79    */
setDaemon(boolean daemon)80   public ThreadFactoryBuilder setDaemon(boolean daemon) {
81     this.daemon = daemon;
82     return this;
83   }
84 
85   /**
86    * Sets the priority for new threads created with this ThreadFactory.
87    *
88    * @param priority the priority for new Threads created with this
89    *     ThreadFactory
90    * @return this for the builder pattern
91    */
setPriority(int priority)92   public ThreadFactoryBuilder setPriority(int priority) {
93     // Thread#setPriority() already checks for validity. These error messages
94     // are nicer though and will fail-fast.
95     checkArgument(priority >= Thread.MIN_PRIORITY,
96         "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY);
97     checkArgument(priority <= Thread.MAX_PRIORITY,
98         "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY);
99     this.priority = priority;
100     return this;
101   }
102 
103   /**
104    * Sets the {@link UncaughtExceptionHandler} for new threads created with this
105    * ThreadFactory.
106    *
107    * @param uncaughtExceptionHandler the uncaught exception handler for new
108    *     Threads created with this ThreadFactory
109    * @return this for the builder pattern
110    */
setUncaughtExceptionHandler( UncaughtExceptionHandler uncaughtExceptionHandler)111   public ThreadFactoryBuilder setUncaughtExceptionHandler(
112       UncaughtExceptionHandler uncaughtExceptionHandler) {
113     this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler);
114     return this;
115   }
116 
117   /**
118    * Sets the backing {@link ThreadFactory} for new threads created with this
119    * ThreadFactory. Threads will be created by invoking #newThread(Runnable) on
120    * this backing {@link ThreadFactory}.
121    *
122    * @param backingThreadFactory the backing {@link ThreadFactory} which will
123    *     be delegated to during thread creation.
124    * @return this for the builder pattern
125    *
126    * @see MoreExecutors
127    */
setThreadFactory( ThreadFactory backingThreadFactory)128   public ThreadFactoryBuilder setThreadFactory(
129       ThreadFactory backingThreadFactory) {
130     this.backingThreadFactory = checkNotNull(backingThreadFactory);
131     return this;
132   }
133 
134   /**
135    * Returns a new thread factory using the options supplied during the building
136    * process. After building, it is still possible to change the options used to
137    * build the ThreadFactory and/or build again. State is not shared amongst
138    * built instances.
139    *
140    * @return the fully constructed {@link ThreadFactory}
141    */
build()142   public ThreadFactory build() {
143     return build(this);
144   }
145 
build(ThreadFactoryBuilder builder)146   private static ThreadFactory build(ThreadFactoryBuilder builder) {
147     final String nameFormat = builder.nameFormat;
148     final Boolean daemon = builder.daemon;
149     final Integer priority = builder.priority;
150     final UncaughtExceptionHandler uncaughtExceptionHandler =
151         builder.uncaughtExceptionHandler;
152     final ThreadFactory backingThreadFactory =
153         (builder.backingThreadFactory != null)
154         ? builder.backingThreadFactory
155         : Executors.defaultThreadFactory();
156     final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
157     return new ThreadFactory() {
158       @Override public Thread newThread(Runnable runnable) {
159         Thread thread = backingThreadFactory.newThread(runnable);
160         if (nameFormat != null) {
161           thread.setName(String.format(nameFormat, count.getAndIncrement()));
162         }
163         if (daemon != null) {
164           thread.setDaemon(daemon);
165         }
166         if (priority != null) {
167           thread.setPriority(priority);
168         }
169         if (uncaughtExceptionHandler != null) {
170           thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
171         }
172         return thread;
173       }
174     };
175   }
176 }
177