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