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