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