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