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