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