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