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 java.lang.Thread.UncaughtExceptionHandler; 024import java.util.Locale; 025import java.util.concurrent.Executors; 026import java.util.concurrent.ThreadFactory; 027import java.util.concurrent.atomic.AtomicLong; 028import javax.annotation.CheckForNull; 029 030/** 031 * A ThreadFactory builder, providing any combination of these features: 032 * 033 * <ul> 034 * <li>whether threads should be marked as {@linkplain Thread#setDaemon daemon} threads 035 * <li>a {@linkplain ThreadFactoryBuilder#setNameFormat naming format} 036 * <li>a {@linkplain Thread#setPriority thread priority} 037 * <li>an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception handler} 038 * <li>a {@linkplain ThreadFactory#newThread backing thread factory} 039 * </ul> 040 * 041 * <p>If no backing thread factory is provided, a default backing thread factory is used as if by 042 * calling {@code setThreadFactory(}{@link Executors#defaultThreadFactory()}{@code )}. 043 * 044 * @author Kurt Alfred Kluever 045 * @since 4.0 046 */ 047@GwtIncompatible 048@ElementTypesAreNonnullByDefault 049public final class ThreadFactoryBuilder { 050 @CheckForNull private String nameFormat = null; 051 @CheckForNull private Boolean daemon = null; 052 @CheckForNull private Integer priority = null; 053 @CheckForNull private UncaughtExceptionHandler uncaughtExceptionHandler = null; 054 @CheckForNull private ThreadFactory backingThreadFactory = null; 055 056 /** Creates a new {@link ThreadFactory} builder. */ 057 public ThreadFactoryBuilder() {} 058 059 /** 060 * Sets the naming format to use when naming threads ({@link Thread#setName}) which are created 061 * with this ThreadFactory. 062 * 063 * @param nameFormat a {@link String#format(String, Object...)}-compatible format String, to which 064 * a unique integer (0, 1, etc.) will be supplied as the single parameter. This integer will 065 * be unique to the built instance of the ThreadFactory and will be assigned sequentially. For 066 * example, {@code "rpc-pool-%d"} will generate thread names like {@code "rpc-pool-0"}, {@code 067 * "rpc-pool-1"}, {@code "rpc-pool-2"}, etc. 068 * @return this for the builder pattern 069 */ 070 @CanIgnoreReturnValue 071 public ThreadFactoryBuilder setNameFormat(String nameFormat) { 072 String unused = format(nameFormat, 0); // fail fast if the format is bad or null 073 this.nameFormat = nameFormat; 074 return this; 075 } 076 077 /** 078 * Sets daemon or not for new threads created with this ThreadFactory. 079 * 080 * @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads 081 * @return this for the builder pattern 082 */ 083 @CanIgnoreReturnValue 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 * <p><b>Warning:</b> relying on the thread scheduler is <a 093 * href="http://errorprone.info/bugpattern/ThreadPriorityCheck">discouraged</a>. 094 * 095 * @param priority the priority for new Threads created with this ThreadFactory 096 * @return this for the builder pattern 097 */ 098 @CanIgnoreReturnValue 099 public ThreadFactoryBuilder setPriority(int priority) { 100 // Thread#setPriority() already checks for validity. These error messages 101 // are nicer though and will fail-fast. 102 checkArgument( 103 priority >= Thread.MIN_PRIORITY, 104 "Thread priority (%s) must be >= %s", 105 priority, 106 Thread.MIN_PRIORITY); 107 checkArgument( 108 priority <= Thread.MAX_PRIORITY, 109 "Thread priority (%s) must be <= %s", 110 priority, 111 Thread.MAX_PRIORITY); 112 this.priority = priority; 113 return this; 114 } 115 116 /** 117 * Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. 118 * 119 * @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with 120 * this ThreadFactory 121 * @return this for the builder pattern 122 */ 123 @CanIgnoreReturnValue 124 public ThreadFactoryBuilder setUncaughtExceptionHandler( 125 UncaughtExceptionHandler uncaughtExceptionHandler) { 126 this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); 127 return this; 128 } 129 130 /** 131 * Sets the backing {@link ThreadFactory} for new threads created with this ThreadFactory. Threads 132 * will be created by invoking #newThread(Runnable) on this backing {@link ThreadFactory}. 133 * 134 * @param backingThreadFactory the backing {@link ThreadFactory} which will be delegated to during 135 * thread creation. 136 * @return this for the builder pattern 137 * @see MoreExecutors 138 */ 139 @CanIgnoreReturnValue 140 public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) { 141 this.backingThreadFactory = checkNotNull(backingThreadFactory); 142 return this; 143 } 144 145 /** 146 * Returns a new thread factory using the options supplied during the building process. After 147 * building, it is still possible to change the options used to build the ThreadFactory and/or 148 * build again. State is not shared amongst built instances. 149 * 150 * @return the fully constructed {@link ThreadFactory} 151 */ 152 public ThreadFactory build() { 153 return doBuild(this); 154 } 155 156 // Split out so that the anonymous ThreadFactory can't contain a reference back to the builder. 157 // At least, I assume that's why. TODO(cpovirk): Check, and maybe add a test for this. 158 private static ThreadFactory doBuild(ThreadFactoryBuilder builder) { 159 String nameFormat = builder.nameFormat; 160 Boolean daemon = builder.daemon; 161 Integer priority = builder.priority; 162 UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; 163 ThreadFactory backingThreadFactory = 164 (builder.backingThreadFactory != null) 165 ? builder.backingThreadFactory 166 : Executors.defaultThreadFactory(); 167 AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; 168 return new ThreadFactory() { 169 @Override 170 public Thread newThread(Runnable runnable) { 171 Thread thread = backingThreadFactory.newThread(runnable); 172 if (nameFormat != null) { 173 // requireNonNull is safe because we create `count` if (and only if) we have a nameFormat. 174 thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement())); 175 } 176 if (daemon != null) { 177 thread.setDaemon(daemon); 178 } 179 if (priority != null) { 180 thread.setPriority(priority); 181 } 182 if (uncaughtExceptionHandler != null) { 183 thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); 184 } 185 return thread; 186 } 187 }; 188 } 189 190 private static String format(String format, Object... args) { 191 return String.format(Locale.ROOT, format, args); 192 } 193}