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