001/* 002 * Copyright (C) 2010 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019import static java.util.Objects.requireNonNull; 020 021import com.google.common.annotations.GwtIncompatible; 022import com.google.errorprone.annotations.CanIgnoreReturnValue; 023import com.google.errorprone.annotations.CheckReturnValue; 024import java.lang.Thread.UncaughtExceptionHandler; 025import java.util.Locale; 026import java.util.concurrent.Executors; 027import java.util.concurrent.ThreadFactory; 028import java.util.concurrent.atomic.AtomicLong; 029import javax.annotation.CheckForNull; 030 031/** 032 * A ThreadFactory builder, providing any combination of these features: 033 * 034 * <ul> 035 * <li>whether threads should be marked as {@linkplain Thread#setDaemon daemon} threads 036 * <li>a {@linkplain ThreadFactoryBuilder#setNameFormat naming format} 037 * <li>a {@linkplain Thread#setPriority thread priority} 038 * <li>an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception handler} 039 * <li>a {@linkplain ThreadFactory#newThread backing thread factory} 040 * </ul> 041 * 042 * <p>If no backing thread factory is provided, a default backing thread factory is used as if by 043 * calling {@code setThreadFactory(}{@link Executors#defaultThreadFactory()}{@code )}. 044 * 045 * @author Kurt Alfred Kluever 046 * @since 4.0 047 */ 048@CanIgnoreReturnValue 049@GwtIncompatible 050@ElementTypesAreNonnullByDefault 051public final class ThreadFactoryBuilder { 052 @CheckForNull private String nameFormat = null; 053 @CheckForNull private Boolean daemon = null; 054 @CheckForNull private Integer priority = null; 055 @CheckForNull private UncaughtExceptionHandler uncaughtExceptionHandler = null; 056 @CheckForNull private ThreadFactory backingThreadFactory = null; 057 058 /** Creates a new {@link ThreadFactory} builder. */ 059 public ThreadFactoryBuilder() {} 060 061 /** 062 * Sets the naming format to use when naming threads ({@link Thread#setName}) which are created 063 * with this ThreadFactory. 064 * 065 * @param nameFormat a {@link String#format(String, Object...)}-compatible format String, to which 066 * a unique integer (0, 1, etc.) will be supplied as the single parameter. This integer will 067 * be unique to the built instance of the ThreadFactory and will be assigned sequentially. For 068 * example, {@code "rpc-pool-%d"} will generate thread names like {@code "rpc-pool-0"}, {@code 069 * "rpc-pool-1"}, {@code "rpc-pool-2"}, etc. 070 * @return this for the builder pattern 071 */ 072 public ThreadFactoryBuilder setNameFormat(String nameFormat) { 073 String unused = format(nameFormat, 0); // fail fast if the format is bad or null 074 this.nameFormat = nameFormat; 075 return this; 076 } 077 078 /** 079 * Sets daemon or not for new threads created with this ThreadFactory. 080 * 081 * @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads 082 * @return this for the builder pattern 083 */ 084 public ThreadFactoryBuilder setDaemon(boolean daemon) { 085 this.daemon = daemon; 086 return this; 087 } 088 089 /** 090 * Sets the priority for new threads created with this ThreadFactory. 091 * 092 * @param priority the priority for new Threads created with this ThreadFactory 093 * @return this for the builder pattern 094 */ 095 public ThreadFactoryBuilder setPriority(int priority) { 096 // Thread#setPriority() already checks for validity. These error messages 097 // are nicer though and will fail-fast. 098 checkArgument( 099 priority >= Thread.MIN_PRIORITY, 100 "Thread priority (%s) must be >= %s", 101 priority, 102 Thread.MIN_PRIORITY); 103 checkArgument( 104 priority <= Thread.MAX_PRIORITY, 105 "Thread priority (%s) must be <= %s", 106 priority, 107 Thread.MAX_PRIORITY); 108 this.priority = priority; 109 return this; 110 } 111 112 /** 113 * Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. 114 * 115 * @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with 116 * this ThreadFactory 117 * @return this for the builder pattern 118 */ 119 public ThreadFactoryBuilder setUncaughtExceptionHandler( 120 UncaughtExceptionHandler uncaughtExceptionHandler) { 121 this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); 122 return this; 123 } 124 125 /** 126 * Sets the backing {@link ThreadFactory} for new threads created with this ThreadFactory. Threads 127 * will be created by invoking #newThread(Runnable) on this backing {@link ThreadFactory}. 128 * 129 * @param backingThreadFactory the backing {@link ThreadFactory} which will be delegated to during 130 * thread creation. 131 * @return this for the builder pattern 132 * @see MoreExecutors 133 */ 134 public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) { 135 this.backingThreadFactory = checkNotNull(backingThreadFactory); 136 return this; 137 } 138 139 /** 140 * Returns a new thread factory using the options supplied during the building process. After 141 * building, it is still possible to change the options used to build the ThreadFactory and/or 142 * build again. State is not shared amongst built instances. 143 * 144 * @return the fully constructed {@link ThreadFactory} 145 */ 146 @CheckReturnValue 147 public ThreadFactory build() { 148 return doBuild(this); 149 } 150 151 // Split out so that the anonymous ThreadFactory can't contain a reference back to the builder. 152 // At least, I assume that's why. TODO(cpovirk): Check, and maybe add a test for this. 153 private static ThreadFactory doBuild(ThreadFactoryBuilder builder) { 154 String nameFormat = builder.nameFormat; 155 Boolean daemon = builder.daemon; 156 Integer priority = builder.priority; 157 UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; 158 ThreadFactory backingThreadFactory = 159 (builder.backingThreadFactory != null) 160 ? builder.backingThreadFactory 161 : Executors.defaultThreadFactory(); 162 AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; 163 return new ThreadFactory() { 164 @Override 165 public Thread newThread(Runnable runnable) { 166 Thread thread = backingThreadFactory.newThread(runnable); 167 if (nameFormat != null) { 168 // requireNonNull is safe because we create `count` if (and only if) we have a nameFormat. 169 thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement())); 170 } 171 if (daemon != null) { 172 thread.setDaemon(daemon); 173 } 174 if (priority != null) { 175 thread.setPriority(priority); 176 } 177 if (uncaughtExceptionHandler != null) { 178 thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); 179 } 180 return thread; 181 } 182 }; 183 } 184 185 private static String format(String format, Object... args) { 186 return String.format(Locale.ROOT, format, args); 187 } 188}