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 java.lang.Thread.UncaughtExceptionHandler;
023import java.util.Locale;
024import java.util.concurrent.Executors;
025import java.util.concurrent.ThreadFactory;
026import java.util.concurrent.atomic.AtomicLong;
027import javax.annotation.CheckReturnValue;
028
029/**
030 * A ThreadFactory builder, providing any combination of these features:
031 * <ul>
032 * <li>whether threads should be marked as {@linkplain Thread#setDaemon daemon} threads
033 * <li>a {@linkplain ThreadFactoryBuilder#setNameFormat naming format}
034 * <li>a {@linkplain Thread#setPriority thread priority}
035 * <li>an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception handler}
036 * <li>a {@linkplain ThreadFactory#newThread backing thread factory}
037 * </ul>
038 * <p>If no backing thread factory is provided, a default backing thread factory is used as if by
039 * calling {@code setThreadFactory(}{@link Executors#defaultThreadFactory()}{@code )}.
040 *
041 * @author Kurt Alfred Kluever
042 * @since 4.0
043 */
044@CanIgnoreReturnValue
045@GwtIncompatible
046public final class ThreadFactoryBuilder {
047  private String nameFormat = null;
048  private Boolean daemon = null;
049  private Integer priority = null;
050  private UncaughtExceptionHandler uncaughtExceptionHandler = null;
051  private ThreadFactory backingThreadFactory = null;
052
053  /**
054   * Creates a new {@link ThreadFactory} builder.
055   */
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"},
066   *     {@code "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   *
130   * @see MoreExecutors
131   */
132  public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) {
133    this.backingThreadFactory = checkNotNull(backingThreadFactory);
134    return this;
135  }
136
137  /**
138   * Returns a new thread factory using the options supplied during the building process. After
139   * building, it is still possible to change the options used to build the ThreadFactory and/or
140   * build again. State is not shared amongst built instances.
141   *
142   * @return the fully constructed {@link ThreadFactory}
143   */
144  @CheckReturnValue
145  public ThreadFactory build() {
146    return build(this);
147  }
148
149  private static ThreadFactory build(ThreadFactoryBuilder builder) {
150    final String nameFormat = builder.nameFormat;
151    final Boolean daemon = builder.daemon;
152    final Integer priority = builder.priority;
153    final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
154    final ThreadFactory backingThreadFactory =
155        (builder.backingThreadFactory != null)
156            ? builder.backingThreadFactory
157            : Executors.defaultThreadFactory();
158    final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
159    return new ThreadFactory() {
160      @Override
161      public Thread newThread(Runnable runnable) {
162        Thread thread = backingThreadFactory.newThread(runnable);
163        if (nameFormat != null) {
164          thread.setName(format(nameFormat, count.getAndIncrement()));
165        }
166        if (daemon != null) {
167          thread.setDaemon(daemon);
168        }
169        if (priority != null) {
170          thread.setPriority(priority);
171        }
172        if (uncaughtExceptionHandler != null) {
173          thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
174        }
175        return thread;
176      }
177    };
178  }
179
180  private static String format(String format, Object... args) {
181    return String.format(Locale.ROOT, format, args);
182  }
183}