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 java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.annotations.J2ktIncompatible;
025import com.google.common.annotations.VisibleForTesting;
026import com.google.common.base.Supplier;
027import com.google.common.base.Throwables;
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.checkerframework.checker.nullness.qual.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)
065@ElementTypesAreNonnullByDefault
066public final class MoreExecutors {
067  private MoreExecutors() {}
068
069  /**
070   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
071   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
072   * completion.
073   *
074   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
075   *
076   * @param executor the executor to modify to make sure it exits when the application is finished
077   * @param terminationTimeout how long to wait for the executor to finish before terminating the
078   *     JVM
079   * @return an unmodifiable version of the input which will not hang the JVM
080   * @since 28.0
081   */
082  @J2ktIncompatible
083  @GwtIncompatible // TODO
084  public static ExecutorService getExitingExecutorService(
085      ThreadPoolExecutor executor, Duration terminationTimeout) {
086    return getExitingExecutorService(
087        executor, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
088  }
089
090  /**
091   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
092   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
093   * completion.
094   *
095   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
096   *
097   * @param executor the executor to modify to make sure it exits when the application is finished
098   * @param terminationTimeout how long to wait for the executor to finish before terminating the
099   *     JVM
100   * @param timeUnit unit of time for the time parameter
101   * @return an unmodifiable version of the input which will not hang the JVM
102   */
103  @J2ktIncompatible
104  @GwtIncompatible // TODO
105  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
106  public static ExecutorService getExitingExecutorService(
107      ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
108    return new Application().getExitingExecutorService(executor, terminationTimeout, timeUnit);
109  }
110
111  /**
112   * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application
113   * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their
114   * completion.
115   *
116   * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor
117   * has not finished its work.
118   *
119   * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}.
120   *
121   * @param executor the executor to modify to make sure it exits when the application is finished
122   * @return an unmodifiable version of the input which will not hang the JVM
123   */
124  @J2ktIncompatible
125  @GwtIncompatible // concurrency
126  public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
127    return new Application().getExitingExecutorService(executor);
128  }
129
130  /**
131   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
132   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
133   * wait for their completion.
134   *
135   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
136   *
137   * @param executor the executor to modify to make sure it exits when the application is finished
138   * @param terminationTimeout how long to wait for the executor to finish before terminating the
139   *     JVM
140   * @return an unmodifiable version of the input which will not hang the JVM
141   * @since 28.0
142   */
143  @J2ktIncompatible
144  @GwtIncompatible // java.time.Duration
145  public static ScheduledExecutorService getExitingScheduledExecutorService(
146      ScheduledThreadPoolExecutor executor, Duration terminationTimeout) {
147    return getExitingScheduledExecutorService(
148        executor, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
149  }
150
151  /**
152   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
153   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
154   * wait for their completion.
155   *
156   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
157   *
158   * @param executor the executor to modify to make sure it exits when the application is finished
159   * @param terminationTimeout how long to wait for the executor to finish before terminating the
160   *     JVM
161   * @param timeUnit unit of time for the time parameter
162   * @return an unmodifiable version of the input which will not hang the JVM
163   */
164  @J2ktIncompatible
165  @GwtIncompatible // TODO
166  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
167  public static ScheduledExecutorService getExitingScheduledExecutorService(
168      ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
169    return new Application()
170        .getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit);
171  }
172
173  /**
174   * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when
175   * the application is complete. It does so by using daemon threads and adding a shutdown hook to
176   * wait for their completion.
177   *
178   * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor
179   * has not finished its work.
180   *
181   * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}.
182   *
183   * @param executor the executor to modify to make sure it exits when the application is finished
184   * @return an unmodifiable version of the input which will not hang the JVM
185   */
186  @J2ktIncompatible
187  @GwtIncompatible // TODO
188  public static ScheduledExecutorService getExitingScheduledExecutorService(
189      ScheduledThreadPoolExecutor executor) {
190    return new Application().getExitingScheduledExecutorService(executor);
191  }
192
193  /**
194   * Add a shutdown hook to wait for thread completion in the given {@link ExecutorService service}.
195   * This is useful if the given service uses daemon threads, and we want to keep the JVM from
196   * exiting immediately on shutdown, instead giving these daemon threads a chance to terminate
197   * normally.
198   *
199   * @param service ExecutorService which uses daemon threads
200   * @param terminationTimeout how long to wait for the executor to finish before terminating the
201   *     JVM
202   * @since 28.0
203   */
204  @J2ktIncompatible
205  @GwtIncompatible // java.time.Duration
206  public static void addDelayedShutdownHook(ExecutorService service, Duration terminationTimeout) {
207    addDelayedShutdownHook(service, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
208  }
209
210  /**
211   * Add a shutdown hook to wait for thread completion in the given {@link ExecutorService service}.
212   * This is useful if the given service uses daemon threads, and we want to keep the JVM from
213   * exiting immediately on shutdown, instead giving these daemon threads a chance to terminate
214   * normally.
215   *
216   * @param service ExecutorService which uses daemon threads
217   * @param terminationTimeout how long to wait for the executor to finish before terminating the
218   *     JVM
219   * @param timeUnit unit of time for the time parameter
220   */
221  @J2ktIncompatible
222  @GwtIncompatible // TODO
223  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
224  public static void addDelayedShutdownHook(
225      ExecutorService service, long terminationTimeout, TimeUnit timeUnit) {
226    new Application().addDelayedShutdownHook(service, terminationTimeout, timeUnit);
227  }
228
229  /** Represents the current application to register shutdown hooks. */
230  @J2ktIncompatible
231  @GwtIncompatible // TODO
232  @VisibleForTesting
233  static class Application {
234
235    final ExecutorService getExitingExecutorService(
236        ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
237      useDaemonThreadFactory(executor);
238      ExecutorService service = Executors.unconfigurableExecutorService(executor);
239      addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
240      return service;
241    }
242
243    final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
244      return getExitingExecutorService(executor, 120, TimeUnit.SECONDS);
245    }
246
247    final ScheduledExecutorService getExitingScheduledExecutorService(
248        ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
249      useDaemonThreadFactory(executor);
250      ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
251      addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
252      return service;
253    }
254
255    final ScheduledExecutorService getExitingScheduledExecutorService(
256        ScheduledThreadPoolExecutor executor) {
257      return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS);
258    }
259
260    final void addDelayedShutdownHook(
261        final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) {
262      checkNotNull(service);
263      checkNotNull(timeUnit);
264      addShutdownHook(
265          MoreExecutors.newThread(
266              "DelayedShutdownHook-for-" + service,
267              new Runnable() {
268                @Override
269                public void run() {
270                  try {
271                    // We'd like to log progress and failures that may arise in the
272                    // following code, but unfortunately the behavior of logging
273                    // is undefined in shutdown hooks.
274                    // This is because the logging code installs a shutdown hook of its
275                    // own. See Cleaner class inside {@link LogManager}.
276                    service.shutdown();
277                    service.awaitTermination(terminationTimeout, timeUnit);
278                  } catch (InterruptedException ignored) {
279                    // We're shutting down anyway, so just ignore.
280                  }
281                }
282              }));
283    }
284
285    @VisibleForTesting
286    void addShutdownHook(Thread hook) {
287      Runtime.getRuntime().addShutdownHook(hook);
288    }
289  }
290
291  @J2ktIncompatible
292  @GwtIncompatible // TODO
293  private static void useDaemonThreadFactory(ThreadPoolExecutor executor) {
294    executor.setThreadFactory(
295        new ThreadFactoryBuilder()
296            .setDaemon(true)
297            .setThreadFactory(executor.getThreadFactory())
298            .build());
299  }
300
301  /**
302   * Creates an executor service that runs each task in the thread that invokes {@code
303   * execute/submit}, as in {@code ThreadPoolExecutor.CallerRunsPolicy}. This applies both to
304   * individually submitted tasks and to collections of tasks submitted via {@code invokeAll} or
305   * {@code invokeAny}. In the latter case, tasks will run serially on the calling thread. Tasks are
306   * run to completion before a {@code Future} is returned to the caller (unless the executor has
307   * been shutdown).
308   *
309   * <p>Although all tasks are immediately executed in the thread that submitted the task, this
310   * {@code ExecutorService} imposes a small locking overhead on each task submission in order to
311   * implement shutdown and termination behavior.
312   *
313   * <p>The implementation deviates from the {@code ExecutorService} specification with regards to
314   * the {@code shutdownNow} method. First, "best-effort" with regards to canceling running tasks is
315   * implemented as "no-effort". No interrupts or other attempts are made to stop threads executing
316   * tasks. Second, the returned list will always be empty, as any submitted task is considered to
317   * have started execution. This applies also to tasks given to {@code invokeAll} or {@code
318   * invokeAny} which are pending serial execution, even the subset of the tasks that have not yet
319   * started execution. It is unclear from the {@code ExecutorService} specification if these should
320   * be included, and it's much easier to implement the interpretation that they not be. Finally, a
321   * call to {@code shutdown} or {@code shutdownNow} may result in concurrent calls to {@code
322   * invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
323   * already have been executed.
324   *
325   * @since 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0)
326   */
327  @GwtIncompatible // TODO
328  public static ListeningExecutorService newDirectExecutorService() {
329    return new DirectExecutorService();
330  }
331
332  /**
333   * Returns an {@link Executor} that runs each task in the thread that invokes {@link
334   * Executor#execute execute}, as in {@code ThreadPoolExecutor.CallerRunsPolicy}.
335   *
336   * <p>This executor is appropriate for tasks that are lightweight and not deeply chained.
337   * Inappropriate {@code directExecutor} usage can cause problems, and these problems can be
338   * difficult to reproduce because they depend on timing. For example:
339   *
340   * <ul>
341   *   <li>When a {@code ListenableFuture} listener is registered to run under {@code
342   *       directExecutor}, the listener can execute in any of three possible threads:
343   *       <ol>
344   *         <li>When a thread attaches a listener to a {@code ListenableFuture} that's already
345   *             complete, the listener runs immediately in that thread.
346   *         <li>When a thread attaches a listener to a {@code ListenableFuture} that's
347   *             <em>in</em>complete and the {@code ListenableFuture} later completes normally, the
348   *             listener runs in the thread that completes the {@code ListenableFuture}.
349   *         <li>When a listener is attached to a {@code ListenableFuture} and the {@code
350   *             ListenableFuture} gets cancelled, the listener runs immediately in the thread that
351   *             cancelled the {@code Future}.
352   *       </ol>
353   *       Given all these possibilities, it is frequently possible for listeners to execute in UI
354   *       threads, RPC network threads, or other latency-sensitive threads. In those cases, slow
355   *       listeners can harm responsiveness, slow the system as a whole, or worse. (See also the
356   *       note about locking below.)
357   *   <li>If many tasks will be triggered by the same event, one heavyweight task may delay other
358   *       tasks -- even tasks that are not themselves {@code directExecutor} tasks.
359   *   <li>If many such tasks are chained together (such as with {@code
360   *       future.transform(...).transform(...).transform(...)....}), they may overflow the stack.
361   *       (In simple cases, callers can avoid this by registering all tasks with the same {@link
362   *       MoreExecutors#newSequentialExecutor} wrapper around {@code directExecutor()}. More
363   *       complex cases may require using thread pools or making deeper changes.)
364   *   <li>If an exception propagates out of a {@code Runnable}, it is not necessarily seen by any
365   *       {@code UncaughtExceptionHandler} for the thread. For example, if the callback passed to
366   *       {@link Futures#addCallback} throws an exception, that exception will be typically be
367   *       logged by the {@link ListenableFuture} implementation, even if the thread is configured
368   *       to do something different. In other cases, no code will catch the exception, and it may
369   *       terminate whichever thread happens to trigger the execution.
370   * </ul>
371   *
372   * A specific warning about locking: Code that executes user-supplied tasks, such as {@code
373   * ListenableFuture} listeners, should take care not to do so while holding a lock. Additionally,
374   * as a further line of defense, prefer not to perform any locking inside a task that will be run
375   * under {@code directExecutor}: Not only might the wait for a lock be long, but if the running
376   * thread was holding a lock, the listener may deadlock or break lock isolation.
377   *
378   * <p>This instance is equivalent to:
379   *
380   * <pre>{@code
381   * final class DirectExecutor implements Executor {
382   *   public void execute(Runnable r) {
383   *     r.run();
384   *   }
385   * }
386   * }</pre>
387   *
388   * <p>This should be preferred to {@link #newDirectExecutorService()} because implementing the
389   * {@link ExecutorService} subinterface necessitates significant performance overhead.
390   *
391   * @since 18.0
392   */
393  public static Executor directExecutor() {
394    return DirectExecutor.INSTANCE;
395  }
396
397  /**
398   * Returns an {@link Executor} that runs each task executed sequentially, such that no two tasks
399   * are running concurrently.
400   *
401   * <p>{@linkplain Executor#execute executed} tasks have a happens-before order as defined in the
402   * Java Language Specification. Tasks execute with the same happens-before order that the function
403   * calls to {@link Executor#execute `execute()`} that submitted those tasks had.
404   *
405   * <p>The executor uses {@code delegate} in order to {@link Executor#execute execute} each task in
406   * turn, and does not create any threads of its own.
407   *
408   * <p>After execution begins on a thread from the {@code delegate} {@link Executor}, tasks are
409   * polled and executed from a task queue until there are no more tasks. The thread will not be
410   * released until there are no more tasks to run.
411   *
412   * <p>If a task is submitted while a thread is executing tasks from the task queue, the thread
413   * will not be released until that submitted task is also complete.
414   *
415   * <p>If a task is {@linkplain Thread#interrupt interrupted} while a task is running:
416   *
417   * <ol>
418   *   <li>execution will not stop until the task queue is empty.
419   *   <li>tasks will begin execution with the thread marked as not interrupted - any interruption
420   *       applies only to the task that was running at the point of interruption.
421   *   <li>if the thread was interrupted before the SequentialExecutor's worker begins execution,
422   *       the interrupt will be restored to the thread after it completes so that its {@code
423   *       delegate} Executor may process the interrupt.
424   *   <li>subtasks are run with the thread uninterrupted and interrupts received during execution
425   *       of a task are ignored.
426   * </ol>
427   *
428   * <p>{@code RuntimeException}s thrown by tasks are simply logged and the executor keeps trucking.
429   * If an {@code Error} is thrown, the error will propagate and execution will stop until the next
430   * time a task is submitted.
431   *
432   * <p>When an {@code Error} is thrown by an executed task, previously submitted tasks may never
433   * run. An attempt will be made to restart execution on the next call to {@code execute}. If the
434   * {@code delegate} has begun to reject execution, the previously submitted tasks may never run,
435   * despite not throwing a RejectedExecutionException synchronously with the call to {@code
436   * execute}. If this behaviour is problematic, use an Executor with a single thread (e.g. {@link
437   * Executors#newSingleThreadExecutor}).
438   *
439   * @since 23.3 (since 23.1 as {@code sequentialExecutor})
440   */
441  @J2ktIncompatible
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  })
685  @J2ktIncompatible
686  @GwtIncompatible
687  @ParametricNullness
688  static <T extends @Nullable Object> T invokeAnyImpl(
689      ListeningExecutorService executorService,
690      Collection<? extends Callable<T>> tasks,
691      boolean timed,
692      long timeout,
693      TimeUnit unit)
694      throws InterruptedException, ExecutionException, TimeoutException {
695    checkNotNull(executorService);
696    checkNotNull(unit);
697    int ntasks = tasks.size();
698    checkArgument(ntasks > 0);
699    List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks);
700    BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue();
701    long timeoutNanos = unit.toNanos(timeout);
702
703    // For efficiency, especially in executors with limited
704    // parallelism, check to see if previously submitted tasks are
705    // done before submitting more of them. This interleaving
706    // plus the exception mechanics account for messiness of main
707    // loop.
708
709    try {
710      // Record exceptions so that if we fail to obtain any
711      // result, we can throw the last exception we got.
712      ExecutionException ee = null;
713      long lastTime = timed ? System.nanoTime() : 0;
714      Iterator<? extends Callable<T>> it = tasks.iterator();
715
716      futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
717      --ntasks;
718      int active = 1;
719
720      while (true) {
721        Future<T> f = futureQueue.poll();
722        if (f == null) {
723          if (ntasks > 0) {
724            --ntasks;
725            futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
726            ++active;
727          } else if (active == 0) {
728            break;
729          } else if (timed) {
730            f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS);
731            if (f == null) {
732              throw new TimeoutException();
733            }
734            long now = System.nanoTime();
735            timeoutNanos -= now - lastTime;
736            lastTime = now;
737          } else {
738            f = futureQueue.take();
739          }
740        }
741        if (f != null) {
742          --active;
743          try {
744            return f.get();
745          } catch (ExecutionException eex) {
746            ee = eex;
747          } catch (InterruptedException iex) {
748            throw iex;
749          } catch (Exception rex) { // sneaky checked exception
750            ee = new ExecutionException(rex);
751          }
752        }
753      }
754
755      if (ee == null) {
756        ee = new ExecutionException(null);
757      }
758      throw ee;
759    } finally {
760      for (Future<T> f : futures) {
761        f.cancel(true);
762      }
763    }
764  }
765
766  /**
767   * Submits the task and adds a listener that adds the future to {@code queue} when it completes.
768   */
769  @J2ktIncompatible
770  @GwtIncompatible // TODO
771  private static <T extends @Nullable Object> ListenableFuture<T> submitAndAddQueueListener(
772      ListeningExecutorService executorService,
773      Callable<T> task,
774      final BlockingQueue<Future<T>> queue) {
775    final ListenableFuture<T> future = executorService.submit(task);
776    future.addListener(
777        new Runnable() {
778          @Override
779          public void run() {
780            queue.add(future);
781          }
782        },
783        directExecutor());
784    return future;
785  }
786
787  /**
788   * Returns a default thread factory used to create new threads.
789   *
790   * <p>When running on AppEngine with access to <a
791   * href="https://cloud.google.com/appengine/docs/standard/java/javadoc/">AppEngine legacy
792   * APIs</a>, this method returns {@code ThreadManager.currentRequestThreadFactory()}. Otherwise,
793   * it returns {@link Executors#defaultThreadFactory()}.
794   *
795   * @since 14.0
796   */
797  @J2ktIncompatible
798  @GwtIncompatible // concurrency
799  public static ThreadFactory platformThreadFactory() {
800    if (!isAppEngineWithApiClasses()) {
801      return Executors.defaultThreadFactory();
802    }
803    try {
804      return (ThreadFactory)
805          Class.forName("com.google.appengine.api.ThreadManager")
806              .getMethod("currentRequestThreadFactory")
807              .invoke(null);
808    } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException e) {
809      throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e);
810    } catch (InvocationTargetException e) {
811      throw Throwables.propagate(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
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}