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