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