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