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.common.annotations.J2ktIncompatible; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 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@J2ktIncompatible 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 @CanIgnoreReturnValue 073 public ThreadFactoryBuilder setNameFormat(String nameFormat) { 074 String unused = format(nameFormat, 0); // fail fast if the format is bad or null 075 this.nameFormat = nameFormat; 076 return this; 077 } 078 079 /** 080 * Sets daemon or not for new threads created with this ThreadFactory. 081 * 082 * @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads 083 * @return this for the builder pattern 084 */ 085 @CanIgnoreReturnValue 086 public ThreadFactoryBuilder setDaemon(boolean daemon) { 087 this.daemon = daemon; 088 return this; 089 } 090 091 /** 092 * Sets the priority for new threads created with this ThreadFactory. 093 * 094 * <p><b>Warning:</b> relying on the thread scheduler is <a 095 * href="http://errorprone.info/bugpattern/ThreadPriorityCheck">discouraged</a>. 096 * 097 * @param priority the priority for new Threads created with this ThreadFactory 098 * @return this for the builder pattern 099 */ 100 @CanIgnoreReturnValue 101 public ThreadFactoryBuilder setPriority(int priority) { 102 // Thread#setPriority() already checks for validity. These error messages 103 // are nicer though and will fail-fast. 104 checkArgument( 105 priority >= Thread.MIN_PRIORITY, 106 "Thread priority (%s) must be >= %s", 107 priority, 108 Thread.MIN_PRIORITY); 109 checkArgument( 110 priority <= Thread.MAX_PRIORITY, 111 "Thread priority (%s) must be <= %s", 112 priority, 113 Thread.MAX_PRIORITY); 114 this.priority = priority; 115 return this; 116 } 117 118 /** 119 * Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. 120 * 121 * @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with 122 * this ThreadFactory 123 * @return this for the builder pattern 124 */ 125 @CanIgnoreReturnValue 126 public ThreadFactoryBuilder setUncaughtExceptionHandler( 127 UncaughtExceptionHandler uncaughtExceptionHandler) { 128 this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); 129 return this; 130 } 131 132 /** 133 * Sets the backing {@link ThreadFactory} for new threads created with this ThreadFactory. Threads 134 * will be created by invoking #newThread(Runnable) on this backing {@link ThreadFactory}. 135 * 136 * @param backingThreadFactory the backing {@link ThreadFactory} which will be delegated to during 137 * thread creation. 138 * @return this for the builder pattern 139 * @see MoreExecutors 140 */ 141 @CanIgnoreReturnValue 142 public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) { 143 this.backingThreadFactory = checkNotNull(backingThreadFactory); 144 return this; 145 } 146 147 /** 148 * Returns a new thread factory using the options supplied during the building process. After 149 * building, it is still possible to change the options used to build the ThreadFactory and/or 150 * build again. State is not shared amongst built instances. 151 * 152 * @return the fully constructed {@link ThreadFactory} 153 */ 154 public ThreadFactory build() { 155 return doBuild(this); 156 } 157 158 // Split out so that the anonymous ThreadFactory can't contain a reference back to the builder. 159 // At least, I assume that's why. TODO(cpovirk): Check, and maybe add a test for this. 160 private static ThreadFactory doBuild(ThreadFactoryBuilder builder) { 161 String nameFormat = builder.nameFormat; 162 Boolean daemon = builder.daemon; 163 Integer priority = builder.priority; 164 UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; 165 ThreadFactory backingThreadFactory = 166 (builder.backingThreadFactory != null) 167 ? builder.backingThreadFactory 168 : Executors.defaultThreadFactory(); 169 AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; 170 return new ThreadFactory() { 171 @Override 172 public Thread newThread(Runnable runnable) { 173 Thread thread = backingThreadFactory.newThread(runnable); 174 // TODO(b/139735208): Figure out what to do when the factory returns null. 175 requireNonNull(thread); 176 if (nameFormat != null) { 177 // requireNonNull is safe because we create `count` if (and only if) we have a nameFormat. 178 thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement())); 179 } 180 if (daemon != null) { 181 thread.setDaemon(daemon); 182 } 183 if (priority != null) { 184 thread.setPriority(priority); 185 } 186 if (uncaughtExceptionHandler != null) { 187 thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); 188 } 189 return thread; 190 } 191 }; 192 } 193 194 private static String format(String format, Object... args) { 195 return String.format(Locale.ROOT, format, args); 196 } 197}