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