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 instance is equivalent to: 437 * 438 * <pre>{@code 439 * final class DirectExecutor implements Executor { 440 * public void execute(Runnable r) { 441 * r.run(); 442 * } 443 * } 444 * }</pre> 445 * 446 * <p>This should be preferred to {@link #newDirectExecutorService()} because implementing the 447 * {@link ExecutorService} subinterface necessitates significant performance overhead. 448 * 449 * 450 * @since 18.0 451 */ 452 public static Executor directExecutor() { 453 return DirectExecutor.INSTANCE; 454 } 455 456 /** 457 * Returns an {@link Executor} that runs each task executed sequentially, such that no two tasks 458 * are running concurrently. Submitted tasks have a happens-before order as defined in the Java 459 * Language Specification. 460 * 461 * <p>The executor uses {@code delegate} in order to {@link Executor#execute execute} each task in 462 * turn, and does not create any threads of its own. 463 * 464 * <p>After execution begins on a thread from the {@code delegate} {@link Executor}, tasks are 465 * polled and executed from a task queue until there are no more tasks. The thread will not be 466 * released until there are no more tasks to run. 467 * 468 * <p>If a task is submitted while a thread is executing tasks from the task queue, the thread 469 * will not be released until that submitted task is also complete. 470 * 471 * <p>If a task is {@linkplain Thread#interrupt interrupted} while a task is running: 472 * 473 * <ol> 474 * <li>execution will not stop until the task queue is empty. 475 * <li>tasks will begin execution with the thread marked as not interrupted - any interruption 476 * applies only to the task that was running at the point of interruption. 477 * <li>if the thread was interrupted before the SequentialExecutor's worker begins execution, 478 * the interrupt will be restored to the thread after it completes so that its {@code 479 * delegate} Executor may process the interrupt. 480 * <li>subtasks are run with the thread uninterrupted and interrupts received during execution 481 * of a task are ignored. 482 * </ol> 483 * 484 * <p>{@code RuntimeException}s thrown by tasks are simply logged and the executor keeps trucking. 485 * If an {@code Error} is thrown, the error will propagate and execution will stop until the next 486 * time a task is submitted. 487 * 488 * <p>When an {@code Error} is thrown by an executed task, previously submitted tasks may never 489 * run. An attempt will be made to restart execution on the next call to {@code execute}. If the 490 * {@code delegate} has begun to reject execution, the previously submitted tasks may never run, 491 * despite not throwing a RejectedExecutionException synchronously with the call to {@code 492 * execute}. If this behaviour is problematic, use an Executor with a single thread (e.g. {@link 493 * Executors#newSingleThreadExecutor}). 494 * 495 * @since 23.3 (since 23.1 as {@code sequentialExecutor}) 496 */ 497 @Beta 498 @GwtIncompatible 499 public static Executor newSequentialExecutor(Executor delegate) { 500 return new SequentialExecutor(delegate); 501 } 502 503 /** 504 * Creates an {@link ExecutorService} whose {@code submit} and {@code invokeAll} methods submit 505 * {@link ListenableFutureTask} instances to the given delegate executor. Those methods, as well 506 * as {@code execute} and {@code invokeAny}, are implemented in terms of calls to {@code 507 * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that 508 * the returned {@code ListeningExecutorService} never calls the delegate's {@code submit}, {@code 509 * invokeAll}, and {@code invokeAny} methods, so any special handling of tasks must be implemented 510 * in the delegate's {@code execute} method or by wrapping the returned {@code 511 * ListeningExecutorService}. 512 * 513 * <p>If the delegate executor was already an instance of {@code ListeningExecutorService}, it is 514 * returned untouched, and the rest of this documentation does not apply. 515 * 516 * @since 10.0 517 */ 518 @GwtIncompatible // TODO 519 public static ListeningExecutorService listeningDecorator(ExecutorService delegate) { 520 return (delegate instanceof ListeningExecutorService) 521 ? (ListeningExecutorService) delegate 522 : (delegate instanceof ScheduledExecutorService) 523 ? new ScheduledListeningDecorator((ScheduledExecutorService) delegate) 524 : new ListeningDecorator(delegate); 525 } 526 527 /** 528 * Creates a {@link ScheduledExecutorService} whose {@code submit} and {@code invokeAll} methods 529 * submit {@link ListenableFutureTask} instances to the given delegate executor. Those methods, as 530 * well as {@code execute} and {@code invokeAny}, are implemented in terms of calls to {@code 531 * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that 532 * the returned {@code ListeningScheduledExecutorService} never calls the delegate's {@code 533 * submit}, {@code invokeAll}, and {@code invokeAny} methods, so any special handling of tasks 534 * must be implemented in the delegate's {@code execute} method or by wrapping the returned {@code 535 * ListeningScheduledExecutorService}. 536 * 537 * <p>If the delegate executor was already an instance of {@code 538 * ListeningScheduledExecutorService}, it is returned untouched, and the rest of this 539 * documentation does not apply. 540 * 541 * @since 10.0 542 */ 543 @GwtIncompatible // TODO 544 public static ListeningScheduledExecutorService listeningDecorator( 545 ScheduledExecutorService delegate) { 546 return (delegate instanceof ListeningScheduledExecutorService) 547 ? (ListeningScheduledExecutorService) delegate 548 : new ScheduledListeningDecorator(delegate); 549 } 550 551 @GwtIncompatible // TODO 552 private static class ListeningDecorator extends AbstractListeningExecutorService { 553 private final ExecutorService delegate; 554 555 ListeningDecorator(ExecutorService delegate) { 556 this.delegate = checkNotNull(delegate); 557 } 558 559 @Override 560 public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { 561 return delegate.awaitTermination(timeout, unit); 562 } 563 564 @Override 565 public final boolean isShutdown() { 566 return delegate.isShutdown(); 567 } 568 569 @Override 570 public final boolean isTerminated() { 571 return delegate.isTerminated(); 572 } 573 574 @Override 575 public final void shutdown() { 576 delegate.shutdown(); 577 } 578 579 @Override 580 public final List<Runnable> shutdownNow() { 581 return delegate.shutdownNow(); 582 } 583 584 @Override 585 public final void execute(Runnable command) { 586 delegate.execute(command); 587 } 588 } 589 590 @GwtIncompatible // TODO 591 private static final class ScheduledListeningDecorator extends ListeningDecorator 592 implements ListeningScheduledExecutorService { 593 @SuppressWarnings("hiding") 594 final ScheduledExecutorService delegate; 595 596 ScheduledListeningDecorator(ScheduledExecutorService delegate) { 597 super(delegate); 598 this.delegate = checkNotNull(delegate); 599 } 600 601 @Override 602 public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { 603 TrustedListenableFutureTask<Void> task = TrustedListenableFutureTask.create(command, null); 604 ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); 605 return new ListenableScheduledTask<>(task, scheduled); 606 } 607 608 @Override 609 public <V> ListenableScheduledFuture<V> schedule( 610 Callable<V> callable, long delay, TimeUnit unit) { 611 TrustedListenableFutureTask<V> task = TrustedListenableFutureTask.create(callable); 612 ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); 613 return new ListenableScheduledTask<V>(task, scheduled); 614 } 615 616 @Override 617 public ListenableScheduledFuture<?> scheduleAtFixedRate( 618 Runnable command, long initialDelay, long period, TimeUnit unit) { 619 NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); 620 ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit); 621 return new ListenableScheduledTask<>(task, scheduled); 622 } 623 624 @Override 625 public ListenableScheduledFuture<?> scheduleWithFixedDelay( 626 Runnable command, long initialDelay, long delay, TimeUnit unit) { 627 NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); 628 ScheduledFuture<?> scheduled = 629 delegate.scheduleWithFixedDelay(task, initialDelay, delay, unit); 630 return new ListenableScheduledTask<>(task, scheduled); 631 } 632 633 private static final class ListenableScheduledTask<V> 634 extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> { 635 636 private final ScheduledFuture<?> scheduledDelegate; 637 638 public ListenableScheduledTask( 639 ListenableFuture<V> listenableDelegate, ScheduledFuture<?> scheduledDelegate) { 640 super(listenableDelegate); 641 this.scheduledDelegate = scheduledDelegate; 642 } 643 644 @Override 645 public boolean cancel(boolean mayInterruptIfRunning) { 646 boolean cancelled = super.cancel(mayInterruptIfRunning); 647 if (cancelled) { 648 // Unless it is cancelled, the delegate may continue being scheduled 649 scheduledDelegate.cancel(mayInterruptIfRunning); 650 651 // TODO(user): Cancel "this" if "scheduledDelegate" is cancelled. 652 } 653 return cancelled; 654 } 655 656 @Override 657 public long getDelay(TimeUnit unit) { 658 return scheduledDelegate.getDelay(unit); 659 } 660 661 @Override 662 public int compareTo(Delayed other) { 663 return scheduledDelegate.compareTo(other); 664 } 665 } 666 667 @GwtIncompatible // TODO 668 private static final class NeverSuccessfulListenableFutureTask 669 extends AbstractFuture.TrustedFuture<Void> implements Runnable { 670 private final Runnable delegate; 671 672 public NeverSuccessfulListenableFutureTask(Runnable delegate) { 673 this.delegate = checkNotNull(delegate); 674 } 675 676 @Override 677 public void run() { 678 try { 679 delegate.run(); 680 } catch (Throwable t) { 681 setException(t); 682 throw Throwables.propagate(t); 683 } 684 } 685 } 686 } 687 688 /* 689 * This following method is a modified version of one found in 690 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30 691 * which contained the following notice: 692 * 693 * Written by Doug Lea with assistance from members of JCP JSR-166 Expert Group and released to 694 * the public domain, as explained at http://creativecommons.org/publicdomain/zero/1.0/ 695 * 696 * Other contributors include Andrew Wright, Jeffrey Hayes, Pat Fisher, Mike Judd. 697 */ 698 699 /** 700 * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService} 701 * implementations. 702 */ 703 @GwtIncompatible static <T> T invokeAnyImpl( 704 ListeningExecutorService executorService, 705 Collection<? extends Callable<T>> tasks, 706 boolean timed, 707 Duration timeout) 708 throws InterruptedException, ExecutionException, TimeoutException { 709 return invokeAnyImpl( 710 executorService, tasks, timed, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); 711 } 712 713 /** 714 * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService} 715 * implementations. 716 */ 717 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 718 @GwtIncompatible static <T> T invokeAnyImpl( 719 ListeningExecutorService executorService, 720 Collection<? extends Callable<T>> tasks, 721 boolean timed, 722 long timeout, 723 TimeUnit unit) 724 throws InterruptedException, ExecutionException, TimeoutException { 725 checkNotNull(executorService); 726 checkNotNull(unit); 727 int ntasks = tasks.size(); 728 checkArgument(ntasks > 0); 729 List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks); 730 BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue(); 731 long timeoutNanos = unit.toNanos(timeout); 732 733 // For efficiency, especially in executors with limited 734 // parallelism, check to see if previously submitted tasks are 735 // done before submitting more of them. This interleaving 736 // plus the exception mechanics account for messiness of main 737 // loop. 738 739 try { 740 // Record exceptions so that if we fail to obtain any 741 // result, we can throw the last exception we got. 742 ExecutionException ee = null; 743 long lastTime = timed ? System.nanoTime() : 0; 744 Iterator<? extends Callable<T>> it = tasks.iterator(); 745 746 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 747 --ntasks; 748 int active = 1; 749 750 while (true) { 751 Future<T> f = futureQueue.poll(); 752 if (f == null) { 753 if (ntasks > 0) { 754 --ntasks; 755 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 756 ++active; 757 } else if (active == 0) { 758 break; 759 } else if (timed) { 760 f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS); 761 if (f == null) { 762 throw new TimeoutException(); 763 } 764 long now = System.nanoTime(); 765 timeoutNanos -= now - lastTime; 766 lastTime = now; 767 } else { 768 f = futureQueue.take(); 769 } 770 } 771 if (f != null) { 772 --active; 773 try { 774 return f.get(); 775 } catch (ExecutionException eex) { 776 ee = eex; 777 } catch (RuntimeException rex) { 778 ee = new ExecutionException(rex); 779 } 780 } 781 } 782 783 if (ee == null) { 784 ee = new ExecutionException(null); 785 } 786 throw ee; 787 } finally { 788 for (Future<T> f : futures) { 789 f.cancel(true); 790 } 791 } 792 } 793 794 /** 795 * Submits the task and adds a listener that adds the future to {@code queue} when it completes. 796 */ 797 @GwtIncompatible // TODO 798 private static <T> ListenableFuture<T> submitAndAddQueueListener( 799 ListeningExecutorService executorService, 800 Callable<T> task, 801 final BlockingQueue<Future<T>> queue) { 802 final ListenableFuture<T> future = executorService.submit(task); 803 future.addListener( 804 new Runnable() { 805 @Override 806 public void run() { 807 queue.add(future); 808 } 809 }, 810 directExecutor()); 811 return future; 812 } 813 814 /** 815 * Returns a default thread factory used to create new threads. 816 * 817 * <p>When running on AppEngine with access to <a 818 * href="https://cloud.google.com/appengine/docs/standard/java/javadoc/">AppEngine legacy 819 * APIs</a>, this method returns {@code ThreadManager.currentRequestThreadFactory()}. Otherwise, 820 * it returns {@link Executors#defaultThreadFactory()}. 821 * 822 * @since 14.0 823 */ 824 @Beta 825 @GwtIncompatible // concurrency 826 public static ThreadFactory platformThreadFactory() { 827 if (!isAppEngineWithApiClasses()) { 828 return Executors.defaultThreadFactory(); 829 } 830 try { 831 return (ThreadFactory) 832 Class.forName("com.google.appengine.api.ThreadManager") 833 .getMethod("currentRequestThreadFactory") 834 .invoke(null); 835 /* 836 * Do not merge the 3 catch blocks below. javac would infer a type of 837 * ReflectiveOperationException, which Animal Sniffer would reject. (Old versions of Android 838 * don't *seem* to mind, but there might be edge cases of which we're unaware.) 839 */ 840 } catch (IllegalAccessException e) { 841 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 842 } catch (ClassNotFoundException e) { 843 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 844 } catch (NoSuchMethodException e) { 845 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 846 } catch (InvocationTargetException e) { 847 throw Throwables.propagate(e.getCause()); 848 } 849 } 850 851 @GwtIncompatible // TODO 852 private static boolean isAppEngineWithApiClasses() { 853 if (System.getProperty("com.google.appengine.runtime.environment") == null) { 854 return false; 855 } 856 try { 857 Class.forName("com.google.appengine.api.utils.SystemProperty"); 858 } catch (ClassNotFoundException e) { 859 return false; 860 } 861 try { 862 // If the current environment is null, we're not inside AppEngine. 863 return Class.forName("com.google.apphosting.api.ApiProxy") 864 .getMethod("getCurrentEnvironment") 865 .invoke(null) 866 != null; 867 } catch (ClassNotFoundException e) { 868 // If ApiProxy doesn't exist, we're not on AppEngine at all. 869 return false; 870 } catch (InvocationTargetException e) { 871 // If ApiProxy throws an exception, we're not in a proper AppEngine environment. 872 return false; 873 } catch (IllegalAccessException e) { 874 // If the method isn't accessible, we're not on a supported version of AppEngine; 875 return false; 876 } catch (NoSuchMethodException e) { 877 // If the method doesn't exist, we're not on a supported version of AppEngine; 878 return false; 879 } 880 } 881 882 /** 883 * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless 884 * changing the name is forbidden by the security manager. 885 */ 886 @GwtIncompatible // concurrency 887 static Thread newThread(String name, Runnable runnable) { 888 checkNotNull(name); 889 checkNotNull(runnable); 890 Thread result = platformThreadFactory().newThread(runnable); 891 try { 892 result.setName(name); 893 } catch (SecurityException e) { 894 // OK if we can't set the name in this environment. 895 } 896 return result; 897 } 898 899 // TODO(lukes): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService? 900 // TODO(lukes): provide overloads that take constant strings? Function<Runnable, String>s to 901 // calculate names? 902 903 /** 904 * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in. 905 * 906 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 907 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 908 * prevents the renaming then it will be skipped but the tasks will still execute. 909 * 910 * 911 * @param executor The executor to decorate 912 * @param nameSupplier The source of names for each task 913 */ 914 @GwtIncompatible // concurrency 915 static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) { 916 checkNotNull(executor); 917 checkNotNull(nameSupplier); 918 return new Executor() { 919 @Override 920 public void execute(Runnable command) { 921 executor.execute(Callables.threadRenaming(command, nameSupplier)); 922 } 923 }; 924 } 925 926 /** 927 * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run 928 * in. 929 * 930 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 931 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 932 * prevents the renaming then it will be skipped but the tasks will still execute. 933 * 934 * 935 * @param service The executor to decorate 936 * @param nameSupplier The source of names for each task 937 */ 938 @GwtIncompatible // concurrency 939 static ExecutorService renamingDecorator( 940 final ExecutorService service, final Supplier<String> nameSupplier) { 941 checkNotNull(service); 942 checkNotNull(nameSupplier); 943 return new WrappingExecutorService(service) { 944 @Override 945 protected <T> Callable<T> wrapTask(Callable<T> callable) { 946 return Callables.threadRenaming(callable, nameSupplier); 947 } 948 949 @Override 950 protected Runnable wrapTask(Runnable command) { 951 return Callables.threadRenaming(command, nameSupplier); 952 } 953 }; 954 } 955 956 /** 957 * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its 958 * tasks run in. 959 * 960 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 961 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 962 * prevents the renaming then it will be skipped but the tasks will still execute. 963 * 964 * 965 * @param service The executor to decorate 966 * @param nameSupplier The source of names for each task 967 */ 968 @GwtIncompatible // concurrency 969 static ScheduledExecutorService renamingDecorator( 970 final ScheduledExecutorService service, final Supplier<String> nameSupplier) { 971 checkNotNull(service); 972 checkNotNull(nameSupplier); 973 return new WrappingScheduledExecutorService(service) { 974 @Override 975 protected <T> Callable<T> wrapTask(Callable<T> callable) { 976 return Callables.threadRenaming(callable, nameSupplier); 977 } 978 979 @Override 980 protected Runnable wrapTask(Runnable command) { 981 return Callables.threadRenaming(command, nameSupplier); 982 } 983 }; 984 } 985 986 /** 987 * Shuts down the given executor service gradually, first disabling new submissions and later, if 988 * necessary, cancelling remaining tasks. 989 * 990 * <p>The method takes the following steps: 991 * 992 * <ol> 993 * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. 994 * <li>awaits executor service termination for half of the specified timeout. 995 * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling 996 * pending tasks and interrupting running tasks. 997 * <li>awaits executor service termination for the other half of the specified timeout. 998 * </ol> 999 * 1000 * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link 1001 * ExecutorService#shutdownNow()} and returns. 1002 * 1003 * @param service the {@code ExecutorService} to shut down 1004 * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate 1005 * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} 1006 * if the call timed out or was interrupted 1007 * @since 28.0 1008 */ 1009 @Beta 1010 @CanIgnoreReturnValue 1011 @GwtIncompatible // java.time.Duration 1012 public static boolean shutdownAndAwaitTermination(ExecutorService service, Duration timeout) { 1013 return shutdownAndAwaitTermination(service, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); 1014 } 1015 1016 /** 1017 * Shuts down the given executor service gradually, first disabling new submissions and later, if 1018 * necessary, cancelling remaining tasks. 1019 * 1020 * <p>The method takes the following steps: 1021 * 1022 * <ol> 1023 * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. 1024 * <li>awaits executor service termination for half of the specified timeout. 1025 * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling 1026 * pending tasks and interrupting running tasks. 1027 * <li>awaits executor service termination for the other half of the specified timeout. 1028 * </ol> 1029 * 1030 * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link 1031 * ExecutorService#shutdownNow()} and returns. 1032 * 1033 * @param service the {@code ExecutorService} to shut down 1034 * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate 1035 * @param unit the time unit of the timeout argument 1036 * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} 1037 * if the call timed out or was interrupted 1038 * @since 17.0 1039 */ 1040 @Beta 1041 @CanIgnoreReturnValue 1042 @GwtIncompatible // concurrency 1043 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 1044 public static boolean shutdownAndAwaitTermination( 1045 ExecutorService service, long timeout, TimeUnit unit) { 1046 long halfTimeoutNanos = unit.toNanos(timeout) / 2; 1047 // Disable new tasks from being submitted 1048 service.shutdown(); 1049 try { 1050 // Wait for half the duration of the timeout for existing tasks to terminate 1051 if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { 1052 // Cancel currently executing tasks 1053 service.shutdownNow(); 1054 // Wait the other half of the timeout for tasks to respond to being cancelled 1055 service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); 1056 } 1057 } catch (InterruptedException ie) { 1058 // Preserve interrupt status 1059 Thread.currentThread().interrupt(); 1060 // (Re-)Cancel if current thread also interrupted 1061 service.shutdownNow(); 1062 } 1063 return service.isTerminated(); 1064 } 1065 1066 /** 1067 * Returns an Executor that will propagate {@link RejectedExecutionException} from the delegate 1068 * executor to the given {@code future}. 1069 * 1070 * <p>Note, the returned executor can only be used once. 1071 */ 1072 static Executor rejectionPropagatingExecutor( 1073 final Executor delegate, final AbstractFuture<?> future) { 1074 checkNotNull(delegate); 1075 checkNotNull(future); 1076 if (delegate == directExecutor()) { 1077 // directExecutor() cannot throw RejectedExecutionException 1078 return delegate; 1079 } 1080 return new Executor() { 1081 boolean thrownFromDelegate = true; 1082 1083 @Override 1084 public void execute(final Runnable command) { 1085 try { 1086 delegate.execute( 1087 new Runnable() { 1088 @Override 1089 public void run() { 1090 thrownFromDelegate = false; 1091 command.run(); 1092 } 1093 1094 @Override 1095 public String toString() { 1096 return command.toString(); 1097 } 1098 }); 1099 } catch (RejectedExecutionException e) { 1100 if (thrownFromDelegate) { 1101 // wrap exception? 1102 future.setException(e); 1103 } 1104 // otherwise it must have been thrown from a transitive call and the delegate runnable 1105 // should have handled it. 1106 } 1107 } 1108 }; 1109 } 1110}