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