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