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