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