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