001/*
002 * Copyright (C) 2007 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 com.google.common.util.concurrent.Internal.toNanosSaturated;
020import static com.google.common.util.concurrent.SneakyThrows.sneakyThrow;
021import static java.util.Objects.requireNonNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.common.annotations.VisibleForTesting;
027import com.google.common.base.Supplier;
028import com.google.common.collect.Lists;
029import com.google.common.collect.Queues;
030import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture;
031import com.google.errorprone.annotations.CanIgnoreReturnValue;
032import java.lang.reflect.InvocationTargetException;
033import java.time.Duration;
034import java.util.Collection;
035import java.util.Iterator;
036import java.util.List;
037import java.util.concurrent.BlockingQueue;
038import java.util.concurrent.Callable;
039import java.util.concurrent.Delayed;
040import java.util.concurrent.ExecutionException;
041import java.util.concurrent.Executor;
042import java.util.concurrent.ExecutorService;
043import java.util.concurrent.Executors;
044import java.util.concurrent.Future;
045import java.util.concurrent.RejectedExecutionException;
046import java.util.concurrent.ScheduledExecutorService;
047import java.util.concurrent.ScheduledFuture;
048import java.util.concurrent.ScheduledThreadPoolExecutor;
049import java.util.concurrent.ThreadFactory;
050import java.util.concurrent.ThreadPoolExecutor;
051import java.util.concurrent.TimeUnit;
052import java.util.concurrent.TimeoutException;
053import org.jspecify.annotations.Nullable;
054
055/**
056 * Factory and utility methods for {@link java.util.concurrent.Executor}, {@link ExecutorService},
057 * and {@link java.util.concurrent.ThreadFactory}.
058 *
059 * @author Eric Fellheimer
060 * @author Kyle Littlefield
061 * @author Justin Mahoney
062 * @since 3.0
063 */
064@GwtCompatible(emulated = true)
065public final class MoreExecutors {
066  private MoreExecutors() {}
067
068  /**
069   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
070   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
071   * completion.
072   *
073   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
074   *
075   * @param executor the executor to modify to make sure it exits when the application is finished
076   * @param terminationTimeout how long to wait for the executor to finish before terminating the
077   *     JVM
078   * @return an unmodifiable version of the input which will not hang the JVM
079   * @since 28.0 (but only since 33.4.0 in the Android flavor)
080   */
081  @J2ktIncompatible
082  @GwtIncompatible // TODO
083  public static ExecutorService getExitingExecutorService(
084      ThreadPoolExecutor executor, Duration terminationTimeout) {
085    return getExitingExecutorService(
086        executor, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
087  }
088
089  /**
090   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
091   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
092   * completion.
093   *
094   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
095   *
096   * @param executor the executor to modify to make sure it exits when the application is finished
097   * @param terminationTimeout how long to wait for the executor to finish before terminating the
098   *     JVM
099   * @param timeUnit unit of time for the time parameter
100   * @return an unmodifiable version of the input which will not hang the JVM
101   */
102  @J2ktIncompatible
103  @GwtIncompatible // TODO
104  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
105  public static ExecutorService getExitingExecutorService(
106      ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
107    return new Application().getExitingExecutorService(executor, terminationTimeout, timeUnit);
108  }
109
110  /**
111   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
112   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
113   * completion.
114   *
115   * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor
116   * has not finished its work.
117   *
118   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
119   *
120   * @param executor the executor to modify to make sure it exits when the application is finished
121   * @return an unmodifiable version of the input which will not hang the JVM
122   */
123  @J2ktIncompatible
124  @GwtIncompatible // concurrency
125  public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
126    return new Application().getExitingExecutorService(executor);
127  }
128
129  /**
130   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
131   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
132   * wait for their completion.
133   *
134   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
135   *
136   * @param executor the executor to modify to make sure it exits when the application is finished
137   * @param terminationTimeout how long to wait for the executor to finish before terminating the
138   *     JVM
139   * @return an unmodifiable version of the input which will not hang the JVM
140   * @since 28.0 (but only since 33.4.0 in the Android flavor)
141   */
142  @J2ktIncompatible
143  @GwtIncompatible // java.time.Duration
144  public static ScheduledExecutorService getExitingScheduledExecutorService(
145      ScheduledThreadPoolExecutor executor, Duration terminationTimeout) {
146    return getExitingScheduledExecutorService(
147        executor, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
148  }
149
150  /**
151   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
152   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
153   * wait for their completion.
154   *
155   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
156   *
157   * @param executor the executor to modify to make sure it exits when the application is finished
158   * @param terminationTimeout how long to wait for the executor to finish before terminating the
159   *     JVM
160   * @param timeUnit unit of time for the time parameter
161   * @return an unmodifiable version of the input which will not hang the JVM
162   */
163  @J2ktIncompatible
164  @GwtIncompatible // TODO
165  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
166  public static ScheduledExecutorService getExitingScheduledExecutorService(
167      ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
168    return new Application()
169        .getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit);
170  }
171
172  /**
173   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
174   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
175   * wait for their completion.
176   *
177   * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor
178   * has not finished its work.
179   *
180   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
181   *
182   * @param executor the executor to modify to make sure it exits when the application is finished
183   * @return an unmodifiable version of the input which will not hang the JVM
184   */
185  @J2ktIncompatible
186  @GwtIncompatible // TODO
187  public static ScheduledExecutorService getExitingScheduledExecutorService(
188      ScheduledThreadPoolExecutor executor) {
189    return new Application().getExitingScheduledExecutorService(executor);
190  }
191
192  /**
193   * Add a shutdown hook to wait for thread completion in the given {@link ExecutorService service}.
194   * This is useful if the given service uses daemon threads, and we want to keep the JVM from
195   * exiting immediately on shutdown, instead giving these daemon threads a chance to terminate
196   * normally.
197   *
198   * @param service ExecutorService which uses daemon threads
199   * @param terminationTimeout how long to wait for the executor to finish before terminating the
200   *     JVM
201   * @since 28.0 (but only since 33.4.0 in the Android flavor)
202   */
203  @J2ktIncompatible
204  @GwtIncompatible // java.time.Duration
205  public static void addDelayedShutdownHook(ExecutorService service, Duration terminationTimeout) {
206    addDelayedShutdownHook(service, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
207  }
208
209  /**
210   * Add a shutdown hook to wait for thread completion in the given {@link ExecutorService service}.
211   * This is useful if the given service uses daemon threads, and we want to keep the JVM from
212   * exiting immediately on shutdown, instead giving these daemon threads a chance to terminate
213   * normally.
214   *
215   * @param service ExecutorService which uses daemon threads
216   * @param terminationTimeout how long to wait for the executor to finish before terminating the
217   *     JVM
218   * @param timeUnit unit of time for the time parameter
219   */
220  @J2ktIncompatible
221  @GwtIncompatible // TODO
222  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
223  public static void addDelayedShutdownHook(
224      ExecutorService service, long terminationTimeout, TimeUnit timeUnit) {
225    new Application().addDelayedShutdownHook(service, terminationTimeout, timeUnit);
226  }
227
228  /** Represents the current application to register shutdown hooks. */
229  @J2ktIncompatible
230  @GwtIncompatible // TODO
231  @VisibleForTesting
232  static class Application {
233
234    final ExecutorService getExitingExecutorService(
235        ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
236      useDaemonThreadFactory(executor);
237      ExecutorService service = Executors.unconfigurableExecutorService(executor);
238      addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
239      return service;
240    }
241
242    final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
243      return getExitingExecutorService(executor, 120, TimeUnit.SECONDS);
244    }
245
246    final ScheduledExecutorService getExitingScheduledExecutorService(
247        ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
248      useDaemonThreadFactory(executor);
249      ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
250      addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
251      return service;
252    }
253
254    final ScheduledExecutorService getExitingScheduledExecutorService(
255        ScheduledThreadPoolExecutor executor) {
256      return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS);
257    }
258
259    final void addDelayedShutdownHook(
260        final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) {
261      checkNotNull(service);
262      checkNotNull(timeUnit);
263      addShutdownHook(
264          MoreExecutors.newThread(
265              "DelayedShutdownHook-for-" + service,
266              new Runnable() {
267                @Override
268                public void run() {
269                  try {
270                    // We'd like to log progress and failures that may arise in the
271                    // following code, but unfortunately the behavior of logging
272                    // is undefined in shutdown hooks.
273                    // This is because the logging code installs a shutdown hook of its
274                    // own. See Cleaner class inside {@link LogManager}.
275                    service.shutdown();
276                    service.awaitTermination(terminationTimeout, timeUnit);
277                  } catch (InterruptedException ignored) {
278                    // We're shutting down anyway, so just ignore.
279                  }
280                }
281              }));
282    }
283
284    @VisibleForTesting
285    void addShutdownHook(Thread hook) {
286      Runtime.getRuntime().addShutdownHook(hook);
287    }
288  }
289
290  @J2ktIncompatible
291  @GwtIncompatible // TODO
292  private static void useDaemonThreadFactory(ThreadPoolExecutor executor) {
293    executor.setThreadFactory(
294        new ThreadFactoryBuilder()
295            .setDaemon(true)
296            .setThreadFactory(executor.getThreadFactory())
297            .build());
298  }
299
300  /**
301   * Creates an executor service that runs each task in the thread that invokes {@code
302   * execute/submit}, as in {@code ThreadPoolExecutor.CallerRunsPolicy}. This applies both to
303   * individually submitted tasks and to collections of tasks submitted via {@code invokeAll} or
304   * {@code invokeAny}. In the latter case, tasks will run serially on the calling thread. Tasks are
305   * run to completion before a {@code Future} is returned to the caller (unless the executor has
306   * been shutdown).
307   *
308   * <p>Although all tasks are immediately executed in the thread that submitted the task, this
309   * {@code ExecutorService} imposes a small locking overhead on each task submission in order to
310   * implement shutdown and termination behavior.
311   *
312   * <p>The implementation deviates from the {@code ExecutorService} specification with regards to
313   * the {@code shutdownNow} method. First, "best-effort" with regards to canceling running tasks is
314   * implemented as "no-effort". No interrupts or other attempts are made to stop threads executing
315   * tasks. Second, the returned list will always be empty, as any submitted task is considered to
316   * have started execution. This applies also to tasks given to {@code invokeAll} or {@code
317   * invokeAny} which are pending serial execution, even the subset of the tasks that have not yet
318   * started execution. It is unclear from the {@code ExecutorService} specification if these should
319   * be included, and it's much easier to implement the interpretation that they not be. Finally, a
320   * call to {@code shutdown} or {@code shutdownNow} may result in concurrent calls to {@code
321   * invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
322   * already have been executed.
323   *
324   * @since 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0)
325   */
326  @GwtIncompatible // TODO
327  public static ListeningExecutorService newDirectExecutorService() {
328    return new DirectExecutorService();
329  }
330
331  /**
332   * Returns an {@link Executor} that runs each task in the thread that invokes {@link
333   * Executor#execute execute}, as in {@code ThreadPoolExecutor.CallerRunsPolicy}.
334   *
335   * <p>This executor is appropriate for tasks that are lightweight and not deeply chained.
336   * Inappropriate {@code directExecutor} usage can cause problems, and these problems can be
337   * difficult to reproduce because they depend on timing. For example:
338   *
339   * <ul>
340   *   <li>When a {@code ListenableFuture} listener is registered to run under {@code
341   *       directExecutor}, the listener can execute in any of three possible threads:
342   *       <ol>
343   *         <li>When a thread attaches a listener to a {@code ListenableFuture} that's already
344   *             complete, the listener runs immediately in that thread.
345   *         <li>When a thread attaches a listener to a {@code ListenableFuture} that's
346   *             <em>in</em>complete and the {@code ListenableFuture} later completes normally, the
347   *             listener runs in the thread that completes the {@code ListenableFuture}.
348   *         <li>When a listener is attached to a {@code ListenableFuture} and the {@code
349   *             ListenableFuture} gets cancelled, the listener runs immediately in the thread that
350   *             cancelled the {@code Future}.
351   *       </ol>
352   *       Given all these possibilities, it is frequently possible for listeners to execute in UI
353   *       threads, RPC network threads, or other latency-sensitive threads. In those cases, slow
354   *       listeners can harm responsiveness, slow the system as a whole, or worse. (See also the
355   *       note about locking below.)
356   *   <li>If many tasks will be triggered by the same event, one heavyweight task may delay other
357   *       tasks -- even tasks that are not themselves {@code directExecutor} tasks.
358   *   <li>If many such tasks are chained together (such as with {@code
359   *       future.transform(...).transform(...).transform(...)....}), they may overflow the stack.
360   *       (In simple cases, callers can avoid this by registering all tasks with the same {@link
361   *       MoreExecutors#newSequentialExecutor} wrapper around {@code directExecutor()}. More
362   *       complex cases may require using thread pools or making deeper changes.)
363   *   <li>If an exception propagates out of a {@code Runnable}, it is not necessarily seen by any
364   *       {@code UncaughtExceptionHandler} for the thread. For example, if the callback passed to
365   *       {@link Futures#addCallback} throws an exception, that exception will be typically be
366   *       logged by the {@link ListenableFuture} implementation, even if the thread is configured
367   *       to do something different. In other cases, no code will catch the exception, and it may
368   *       terminate whichever thread happens to trigger the execution.
369   * </ul>
370   *
371   * A specific warning about locking: Code that executes user-supplied tasks, such as {@code
372   * ListenableFuture} listeners, should take care not to do so while holding a lock. Additionally,
373   * as a further line of defense, prefer not to perform any locking inside a task that will be run
374   * under {@code directExecutor}: Not only might the wait for a lock be long, but if the running
375   * thread was holding a lock, the listener may deadlock or break lock isolation.
376   *
377   * <p>This instance is equivalent to:
378   *
379   * <pre>{@code
380   * final class DirectExecutor implements Executor {
381   *   public void execute(Runnable r) {
382   *     r.run();
383   *   }
384   * }
385   * }</pre>
386   *
387   * <p>This should be preferred to {@link #newDirectExecutorService()} because implementing the
388   * {@link ExecutorService} subinterface necessitates significant performance overhead.
389   *
390   * @since 18.0
391   */
392  public static Executor directExecutor() {
393    return DirectExecutor.INSTANCE;
394  }
395
396  /**
397   * Returns an {@link Executor} that runs each task executed sequentially, such that no two tasks
398   * are running concurrently.
399   *
400   * <p>{@linkplain Executor#execute executed} tasks have a happens-before order as defined in the
401   * Java Language Specification. Tasks execute with the same happens-before order that the function
402   * calls to {@link Executor#execute execute()} that submitted those tasks had.
403   *
404   * <p>The executor uses {@code delegate} in order to {@link Executor#execute execute} each task in
405   * turn, and does not create any threads of its own.
406   *
407   * <p>After execution begins on a thread from the {@code delegate} {@link Executor}, tasks are
408   * polled and executed from a task queue until there are no more tasks. The thread will not be
409   * released until there are no more tasks to run.
410   *
411   * <p>If a task is submitted while a thread is executing tasks from the task queue, the thread
412   * will not be released until that submitted task is also complete.
413   *
414   * <p>If a task is {@linkplain Thread#interrupt interrupted} while a task is running:
415   *
416   * <ol>
417   *   <li>execution will not stop until the task queue is empty.
418   *   <li>tasks will begin execution with the thread marked as not interrupted - any interruption
419   *       applies only to the task that was running at the point of interruption.
420   *   <li>if the thread was interrupted before the SequentialExecutor's worker begins execution,
421   *       the interrupt will be restored to the thread after it completes so that its {@code
422   *       delegate} Executor may process the interrupt.
423   *   <li>subtasks are run with the thread uninterrupted and interrupts received during execution
424   *       of a task are ignored.
425   * </ol>
426   *
427   * <p>{@code RuntimeException}s thrown by tasks are simply logged and the executor keeps trucking.
428   * If an {@code Error} is thrown, the error will propagate and execution will stop until the next
429   * time a task is submitted.
430   *
431   * <p>When an {@code Error} is thrown by an executed task, previously submitted tasks may never
432   * run. An attempt will be made to restart execution on the next call to {@code execute}. If the
433   * {@code delegate} has begun to reject execution, the previously submitted tasks may never run,
434   * despite not throwing a RejectedExecutionException synchronously with the call to {@code
435   * execute}. If this behaviour is problematic, use an Executor with a single thread (e.g. {@link
436   * Executors#newSingleThreadExecutor}).
437   *
438   * @since 23.3 (since 23.1 as {@code sequentialExecutor})
439   */
440  @GwtIncompatible
441  public static Executor newSequentialExecutor(Executor delegate) {
442    return new SequentialExecutor(delegate);
443  }
444
445  /**
446   * Creates an {@link ExecutorService} whose {@code submit} and {@code invokeAll} methods submit
447   * {@link ListenableFutureTask} instances to the given delegate executor. Those methods, as well
448   * as {@code execute} and {@code invokeAny}, are implemented in terms of calls to {@code
449   * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that
450   * the returned {@code ListeningExecutorService} never calls the delegate's {@code submit}, {@code
451   * invokeAll}, and {@code invokeAny} methods, so any special handling of tasks must be implemented
452   * in the delegate's {@code execute} method or by wrapping the returned {@code
453   * ListeningExecutorService}.
454   *
455   * <p>If the delegate executor was already an instance of {@code ListeningExecutorService}, it is
456   * returned untouched, and the rest of this documentation does not apply.
457   *
458   * @since 10.0
459   */
460  @J2ktIncompatible
461  @GwtIncompatible // TODO
462  public static ListeningExecutorService listeningDecorator(ExecutorService delegate) {
463    return (delegate instanceof ListeningExecutorService)
464        ? (ListeningExecutorService) delegate
465        : (delegate instanceof ScheduledExecutorService)
466            ? new ScheduledListeningDecorator((ScheduledExecutorService) delegate)
467            : new ListeningDecorator(delegate);
468  }
469
470  /**
471   * Creates a {@link ScheduledExecutorService} whose {@code submit} and {@code invokeAll} methods
472   * submit {@link ListenableFutureTask} instances to the given delegate executor. Those methods, as
473   * well as {@code execute} and {@code invokeAny}, are implemented in terms of calls to {@code
474   * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that
475   * the returned {@code ListeningScheduledExecutorService} never calls the delegate's {@code
476   * submit}, {@code invokeAll}, and {@code invokeAny} methods, so any special handling of tasks
477   * must be implemented in the delegate's {@code execute} method or by wrapping the returned {@code
478   * ListeningScheduledExecutorService}.
479   *
480   * <p>If the delegate executor was already an instance of {@code
481   * ListeningScheduledExecutorService}, it is returned untouched, and the rest of this
482   * documentation does not apply.
483   *
484   * @since 10.0
485   */
486  @J2ktIncompatible
487  @GwtIncompatible // TODO
488  public static ListeningScheduledExecutorService listeningDecorator(
489      ScheduledExecutorService delegate) {
490    return (delegate instanceof ListeningScheduledExecutorService)
491        ? (ListeningScheduledExecutorService) delegate
492        : new ScheduledListeningDecorator(delegate);
493  }
494
495  @J2ktIncompatible
496  @GwtIncompatible // TODO
497  private static class ListeningDecorator extends AbstractListeningExecutorService {
498    private final ExecutorService delegate;
499
500    ListeningDecorator(ExecutorService delegate) {
501      this.delegate = checkNotNull(delegate);
502    }
503
504    @Override
505    public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
506      return delegate.awaitTermination(timeout, unit);
507    }
508
509    @Override
510    public final boolean isShutdown() {
511      return delegate.isShutdown();
512    }
513
514    @Override
515    public final boolean isTerminated() {
516      return delegate.isTerminated();
517    }
518
519    @Override
520    public final void shutdown() {
521      delegate.shutdown();
522    }
523
524    @Override
525    public final List<Runnable> shutdownNow() {
526      return delegate.shutdownNow();
527    }
528
529    @Override
530    public final void execute(Runnable command) {
531      delegate.execute(command);
532    }
533
534    @Override
535    public final String toString() {
536      return super.toString() + "[" + delegate + "]";
537    }
538  }
539
540  @J2ktIncompatible
541  @GwtIncompatible // TODO
542  private static final class ScheduledListeningDecorator extends ListeningDecorator
543      implements ListeningScheduledExecutorService {
544    @SuppressWarnings("hiding")
545    final ScheduledExecutorService delegate;
546
547    ScheduledListeningDecorator(ScheduledExecutorService delegate) {
548      super(delegate);
549      this.delegate = checkNotNull(delegate);
550    }
551
552    @Override
553    public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
554      TrustedListenableFutureTask<@Nullable Void> task =
555          TrustedListenableFutureTask.create(command, null);
556      ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit);
557      return new ListenableScheduledTask<@Nullable Void>(task, scheduled);
558    }
559
560    @Override
561    public <V extends @Nullable Object> ListenableScheduledFuture<V> schedule(
562        Callable<V> callable, long delay, TimeUnit unit) {
563      TrustedListenableFutureTask<V> task = TrustedListenableFutureTask.create(callable);
564      ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit);
565      return new ListenableScheduledTask<>(task, scheduled);
566    }
567
568    @Override
569    public ListenableScheduledFuture<?> scheduleAtFixedRate(
570        Runnable command, long initialDelay, long period, TimeUnit unit) {
571      NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command);
572      ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit);
573      return new ListenableScheduledTask<@Nullable Void>(task, scheduled);
574    }
575
576    @Override
577    public ListenableScheduledFuture<?> scheduleWithFixedDelay(
578        Runnable command, long initialDelay, long delay, TimeUnit unit) {
579      NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command);
580      ScheduledFuture<?> scheduled =
581          delegate.scheduleWithFixedDelay(task, initialDelay, delay, unit);
582      return new ListenableScheduledTask<@Nullable Void>(task, scheduled);
583    }
584
585    private static final class ListenableScheduledTask<V extends @Nullable Object>
586        extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> {
587
588      private final ScheduledFuture<?> scheduledDelegate;
589
590      public ListenableScheduledTask(
591          ListenableFuture<V> listenableDelegate, ScheduledFuture<?> scheduledDelegate) {
592        super(listenableDelegate);
593        this.scheduledDelegate = scheduledDelegate;
594      }
595
596      @Override
597      public boolean cancel(boolean mayInterruptIfRunning) {
598        boolean cancelled = super.cancel(mayInterruptIfRunning);
599        if (cancelled) {
600          // Unless it is cancelled, the delegate may continue being scheduled
601          scheduledDelegate.cancel(mayInterruptIfRunning);
602
603          // TODO(user): Cancel "this" if "scheduledDelegate" is cancelled.
604        }
605        return cancelled;
606      }
607
608      @Override
609      public long getDelay(TimeUnit unit) {
610        return scheduledDelegate.getDelay(unit);
611      }
612
613      @Override
614      public int compareTo(Delayed other) {
615        return scheduledDelegate.compareTo(other);
616      }
617    }
618
619    @J2ktIncompatible
620    @GwtIncompatible // TODO
621    private static final class NeverSuccessfulListenableFutureTask
622        extends AbstractFuture.TrustedFuture<@Nullable Void> implements Runnable {
623      private final Runnable delegate;
624
625      public NeverSuccessfulListenableFutureTask(Runnable delegate) {
626        this.delegate = checkNotNull(delegate);
627      }
628
629      @Override
630      public void run() {
631        try {
632          delegate.run();
633        } catch (Throwable t) {
634          // Any Exception is either a RuntimeException or sneaky checked exception.
635          setException(t);
636          throw t;
637        }
638      }
639
640      @Override
641      protected String pendingToString() {
642        return "task=[" + delegate + "]";
643      }
644    }
645  }
646
647  /*
648   * This following method is a modified version of one found in
649   * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30
650   * which contained the following notice:
651   *
652   * Written by Doug Lea with assistance from members of JCP JSR-166 Expert Group and released to
653   * the public domain, as explained at http://creativecommons.org/publicdomain/zero/1.0/
654   *
655   * Other contributors include Andrew Wright, Jeffrey Hayes, Pat Fisher, Mike Judd.
656   */
657
658  /**
659   * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService}
660   * implementations.
661   */
662  @J2ktIncompatible
663  @GwtIncompatible
664  @ParametricNullness
665  static <T extends @Nullable Object> T invokeAnyImpl(
666      ListeningExecutorService executorService,
667      Collection<? extends Callable<T>> tasks,
668      boolean timed,
669      Duration timeout)
670      throws InterruptedException, ExecutionException, TimeoutException {
671    return invokeAnyImpl(
672        executorService, tasks, timed, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
673  }
674
675  /**
676   * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService}
677   * implementations.
678   */
679  @SuppressWarnings({
680    "GoodTime", // should accept a java.time.Duration
681    "CatchingUnchecked", // sneaky checked exception
682    "Interruption", // We copy AbstractExecutorService.invokeAny. Maybe we shouldn't: b/227335009.
683  })
684  @J2ktIncompatible
685  @GwtIncompatible
686  @ParametricNullness
687  static <T extends @Nullable Object> T invokeAnyImpl(
688      ListeningExecutorService executorService,
689      Collection<? extends Callable<T>> tasks,
690      boolean timed,
691      long timeout,
692      TimeUnit unit)
693      throws InterruptedException, ExecutionException, TimeoutException {
694    checkNotNull(executorService);
695    checkNotNull(unit);
696    int ntasks = tasks.size();
697    checkArgument(ntasks > 0);
698    List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks);
699    BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue();
700    long timeoutNanos = unit.toNanos(timeout);
701
702    // For efficiency, especially in executors with limited
703    // parallelism, check to see if previously submitted tasks are
704    // done before submitting more of them. This interleaving
705    // plus the exception mechanics account for messiness of main
706    // loop.
707
708    try {
709      // Record exceptions so that if we fail to obtain any
710      // result, we can throw the last exception we got.
711      ExecutionException ee = null;
712      long lastTime = timed ? System.nanoTime() : 0;
713      Iterator<? extends Callable<T>> it = tasks.iterator();
714
715      futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
716      --ntasks;
717      int active = 1;
718
719      while (true) {
720        Future<T> f = futureQueue.poll();
721        if (f == null) {
722          if (ntasks > 0) {
723            --ntasks;
724            futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
725            ++active;
726          } else if (active == 0) {
727            break;
728          } else if (timed) {
729            f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS);
730            if (f == null) {
731              throw new TimeoutException();
732            }
733            long now = System.nanoTime();
734            timeoutNanos -= now - lastTime;
735            lastTime = now;
736          } else {
737            f = futureQueue.take();
738          }
739        }
740        if (f != null) {
741          --active;
742          try {
743            return f.get();
744          } catch (ExecutionException eex) {
745            ee = eex;
746          } catch (InterruptedException iex) {
747            throw iex;
748          } catch (Exception rex) { // sneaky checked exception
749            ee = new ExecutionException(rex);
750          }
751        }
752      }
753
754      if (ee == null) {
755        ee = new ExecutionException(null);
756      }
757      throw ee;
758    } finally {
759      for (Future<T> f : futures) {
760        f.cancel(true);
761      }
762    }
763  }
764
765  /**
766   * Submits the task and adds a listener that adds the future to {@code queue} when it completes.
767   */
768  @J2ktIncompatible
769  @GwtIncompatible // TODO
770  private static <T extends @Nullable Object> ListenableFuture<T> submitAndAddQueueListener(
771      ListeningExecutorService executorService,
772      Callable<T> task,
773      final BlockingQueue<Future<T>> queue) {
774    final ListenableFuture<T> future = executorService.submit(task);
775    future.addListener(
776        new Runnable() {
777          @Override
778          public void run() {
779            queue.add(future);
780          }
781        },
782        directExecutor());
783    return future;
784  }
785
786  /**
787   * Returns a default thread factory used to create new threads.
788   *
789   * <p>When running on AppEngine with access to <a
790   * href="https://cloud.google.com/appengine/docs/standard/java/javadoc/">AppEngine legacy
791   * APIs</a>, this method returns {@code ThreadManager.currentRequestThreadFactory()}. Otherwise,
792   * it returns {@link Executors#defaultThreadFactory()}.
793   *
794   * @since 14.0
795   */
796  @J2ktIncompatible
797  @GwtIncompatible // concurrency
798  public static ThreadFactory platformThreadFactory() {
799    if (!isAppEngineWithApiClasses()) {
800      return Executors.defaultThreadFactory();
801    }
802    try {
803      return (ThreadFactory)
804          Class.forName("com.google.appengine.api.ThreadManager")
805              .getMethod("currentRequestThreadFactory")
806              .invoke(null);
807    } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException e) {
808      throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e);
809    } catch (InvocationTargetException e) {
810      // `currentRequestThreadFactory` has no `throws` clause.
811      throw sneakyThrow(e.getCause());
812    }
813  }
814
815  @J2ktIncompatible
816  @GwtIncompatible // TODO
817  private static boolean isAppEngineWithApiClasses() {
818    if (System.getProperty("com.google.appengine.runtime.environment") == null) {
819      return false;
820    }
821    try {
822      Class.forName("com.google.appengine.api.utils.SystemProperty");
823    } catch (ClassNotFoundException e) {
824      return false;
825    }
826    try {
827      // If the current environment is null, we're not inside AppEngine.
828      return Class.forName("com.google.apphosting.api.ApiProxy")
829              .getMethod("getCurrentEnvironment")
830              .invoke(null)
831          != null;
832    } catch (ClassNotFoundException e) {
833      // If ApiProxy doesn't exist, we're not on AppEngine at all.
834      return false;
835    } catch (InvocationTargetException e) {
836      // If ApiProxy throws an exception, we're not in a proper AppEngine environment.
837      return false;
838    } catch (IllegalAccessException e) {
839      // If the method isn't accessible, we're not on a supported version of AppEngine;
840      return false;
841    } catch (NoSuchMethodException e) {
842      // If the method doesn't exist, we're not on a supported version of AppEngine;
843      return false;
844    }
845  }
846
847  /**
848   * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless
849   * changing the name is forbidden by the security manager.
850   */
851  @J2ktIncompatible
852  @GwtIncompatible // concurrency
853  static Thread newThread(String name, Runnable runnable) {
854    checkNotNull(name);
855    checkNotNull(runnable);
856    // TODO(b/139726489): Confirm that null is impossible here.
857    Thread result = requireNonNull(platformThreadFactory().newThread(runnable));
858    try {
859      result.setName(name);
860    } catch (SecurityException e) {
861      // OK if we can't set the name in this environment.
862    }
863    return result;
864  }
865
866  // TODO(lukes): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService?
867  // TODO(lukes): provide overloads that take constant strings? Function<Runnable, String>s to
868  // calculate names?
869
870  /**
871   * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in.
872   *
873   * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed
874   * right before each task is run. The renaming is best effort, if a {@link SecurityManager}
875   * prevents the renaming then it will be skipped but the tasks will still execute.
876   *
877   * @param executor The executor to decorate
878   * @param nameSupplier The source of names for each task
879   */
880  @J2ktIncompatible
881  @GwtIncompatible // concurrency
882  static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) {
883    checkNotNull(executor);
884    checkNotNull(nameSupplier);
885    return new Executor() {
886      @Override
887      public void execute(Runnable command) {
888        executor.execute(Callables.threadRenaming(command, nameSupplier));
889      }
890    };
891  }
892
893  /**
894   * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run
895   * in.
896   *
897   * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed
898   * right before each task is run. The renaming is best effort, if a {@link SecurityManager}
899   * prevents the renaming then it will be skipped but the tasks will still execute.
900   *
901   * @param service The executor to decorate
902   * @param nameSupplier The source of names for each task
903   */
904  @J2ktIncompatible
905  @GwtIncompatible // concurrency
906  static ExecutorService renamingDecorator(
907      final ExecutorService service, final Supplier<String> nameSupplier) {
908    checkNotNull(service);
909    checkNotNull(nameSupplier);
910    return new WrappingExecutorService(service) {
911      @Override
912      protected <T extends @Nullable Object> Callable<T> wrapTask(Callable<T> callable) {
913        return Callables.threadRenaming(callable, nameSupplier);
914      }
915
916      @Override
917      protected Runnable wrapTask(Runnable command) {
918        return Callables.threadRenaming(command, nameSupplier);
919      }
920    };
921  }
922
923  /**
924   * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its
925   * tasks run in.
926   *
927   * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed
928   * right before each task is run. The renaming is best effort, if a {@link SecurityManager}
929   * prevents the renaming then it will be skipped but the tasks will still execute.
930   *
931   * @param service The executor to decorate
932   * @param nameSupplier The source of names for each task
933   */
934  @J2ktIncompatible
935  @GwtIncompatible // concurrency
936  static ScheduledExecutorService renamingDecorator(
937      final ScheduledExecutorService service, final Supplier<String> nameSupplier) {
938    checkNotNull(service);
939    checkNotNull(nameSupplier);
940    return new WrappingScheduledExecutorService(service) {
941      @Override
942      protected <T extends @Nullable Object> Callable<T> wrapTask(Callable<T> callable) {
943        return Callables.threadRenaming(callable, nameSupplier);
944      }
945
946      @Override
947      protected Runnable wrapTask(Runnable command) {
948        return Callables.threadRenaming(command, nameSupplier);
949      }
950    };
951  }
952
953  /**
954   * Shuts down the given executor service gradually, first disabling new submissions and later, if
955   * necessary, cancelling remaining tasks.
956   *
957   * <p>The method takes the following steps:
958   *
959   * <ol>
960   *   <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks.
961   *   <li>awaits executor service termination for half of the specified timeout.
962   *   <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling
963   *       pending tasks and interrupting running tasks.
964   *   <li>awaits executor service termination for the other half of the specified timeout.
965   * </ol>
966   *
967   * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link
968   * ExecutorService#shutdownNow()} and returns.
969   *
970   * @param service the {@code ExecutorService} to shut down
971   * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate
972   * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false}
973   *     if the call timed out or was interrupted
974   * @since 28.0 (but only since 33.4.0 in the Android flavor)
975   */
976  @CanIgnoreReturnValue
977  @J2ktIncompatible
978  @GwtIncompatible // java.time.Duration
979  public static boolean shutdownAndAwaitTermination(ExecutorService service, Duration timeout) {
980    return shutdownAndAwaitTermination(service, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
981  }
982
983  /**
984   * Shuts down the given executor service gradually, first disabling new submissions and later, if
985   * necessary, cancelling remaining tasks.
986   *
987   * <p>The method takes the following steps:
988   *
989   * <ol>
990   *   <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks.
991   *   <li>awaits executor service termination for half of the specified timeout.
992   *   <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling
993   *       pending tasks and interrupting running tasks.
994   *   <li>awaits executor service termination for the other half of the specified timeout.
995   * </ol>
996   *
997   * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link
998   * ExecutorService#shutdownNow()} and returns.
999   *
1000   * @param service the {@code ExecutorService} to shut down
1001   * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate
1002   * @param unit the time unit of the timeout argument
1003   * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false}
1004   *     if the call timed out or was interrupted
1005   * @since 17.0
1006   */
1007  @CanIgnoreReturnValue
1008  @J2ktIncompatible
1009  @GwtIncompatible // concurrency
1010  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1011  public static boolean shutdownAndAwaitTermination(
1012      ExecutorService service, long timeout, TimeUnit unit) {
1013    long halfTimeoutNanos = unit.toNanos(timeout) / 2;
1014    // Disable new tasks from being submitted
1015    service.shutdown();
1016    try {
1017      // Wait for half the duration of the timeout for existing tasks to terminate
1018      if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) {
1019        // Cancel currently executing tasks
1020        service.shutdownNow();
1021        // Wait the other half of the timeout for tasks to respond to being cancelled
1022        service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS);
1023      }
1024    } catch (InterruptedException ie) {
1025      // Preserve interrupt status
1026      Thread.currentThread().interrupt();
1027      // (Re-)Cancel if current thread also interrupted
1028      service.shutdownNow();
1029    }
1030    return service.isTerminated();
1031  }
1032
1033  /**
1034   * Returns an Executor that will propagate {@link RejectedExecutionException} from the delegate
1035   * executor to the given {@code future}.
1036   *
1037   * <p>Note, the returned executor can only be used once.
1038   */
1039  static Executor rejectionPropagatingExecutor(
1040      final Executor delegate, final AbstractFuture<?> future) {
1041    checkNotNull(delegate);
1042    checkNotNull(future);
1043    if (delegate == directExecutor()) {
1044      // directExecutor() cannot throw RejectedExecutionException
1045      return delegate;
1046    }
1047    return new Executor() {
1048      @Override
1049      public void execute(Runnable command) {
1050        try {
1051          delegate.execute(command);
1052        } catch (RejectedExecutionException e) {
1053          future.setException(e);
1054        }
1055      }
1056    };
1057  }
1058}