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.base.Throwables.throwIfUnchecked; 020import static com.google.common.util.concurrent.Internal.toNanosSaturated; 021import static java.util.Objects.requireNonNull; 022 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 025import com.google.common.annotations.J2ktIncompatible; 026import com.google.common.annotations.VisibleForTesting; 027import com.google.common.base.Supplier; 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.lang.reflect.UndeclaredThrowableException; 034import java.time.Duration; 035import java.util.Collection; 036import java.util.Iterator; 037import java.util.List; 038import java.util.concurrent.BlockingQueue; 039import java.util.concurrent.Callable; 040import java.util.concurrent.Delayed; 041import java.util.concurrent.ExecutionException; 042import java.util.concurrent.Executor; 043import java.util.concurrent.ExecutorService; 044import java.util.concurrent.Executors; 045import java.util.concurrent.Future; 046import java.util.concurrent.RejectedExecutionException; 047import java.util.concurrent.ScheduledExecutorService; 048import java.util.concurrent.ScheduledFuture; 049import java.util.concurrent.ScheduledThreadPoolExecutor; 050import java.util.concurrent.ThreadFactory; 051import java.util.concurrent.ThreadPoolExecutor; 052import java.util.concurrent.TimeUnit; 053import java.util.concurrent.TimeoutException; 054import org.checkerframework.checker.nullness.qual.Nullable; 055 056/** 057 * Factory and utility methods for {@link java.util.concurrent.Executor}, {@link ExecutorService}, 058 * and {@link java.util.concurrent.ThreadFactory}. 059 * 060 * @author Eric Fellheimer 061 * @author Kyle Littlefield 062 * @author Justin Mahoney 063 * @since 3.0 064 */ 065@GwtCompatible(emulated = true) 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 (but only since 33.4.0 in the Android flavor) 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 (but only since 33.4.0 in the Android flavor) 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 (but only since 33.4.0 in the Android flavor) 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 "Interruption", // We copy AbstractExecutorService.invokeAny. Maybe we shouldn't: b/227335009. 684 }) 685 @J2ktIncompatible 686 @GwtIncompatible 687 @ParametricNullness 688 static <T extends @Nullable Object> T invokeAnyImpl( 689 ListeningExecutorService executorService, 690 Collection<? extends Callable<T>> tasks, 691 boolean timed, 692 long timeout, 693 TimeUnit unit) 694 throws InterruptedException, ExecutionException, TimeoutException { 695 checkNotNull(executorService); 696 checkNotNull(unit); 697 int ntasks = tasks.size(); 698 checkArgument(ntasks > 0); 699 List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks); 700 BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue(); 701 long timeoutNanos = unit.toNanos(timeout); 702 703 // For efficiency, especially in executors with limited 704 // parallelism, check to see if previously submitted tasks are 705 // done before submitting more of them. This interleaving 706 // plus the exception mechanics account for messiness of main 707 // loop. 708 709 try { 710 // Record exceptions so that if we fail to obtain any 711 // result, we can throw the last exception we got. 712 ExecutionException ee = null; 713 long lastTime = timed ? System.nanoTime() : 0; 714 Iterator<? extends Callable<T>> it = tasks.iterator(); 715 716 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 717 --ntasks; 718 int active = 1; 719 720 while (true) { 721 Future<T> f = futureQueue.poll(); 722 if (f == null) { 723 if (ntasks > 0) { 724 --ntasks; 725 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 726 ++active; 727 } else if (active == 0) { 728 break; 729 } else if (timed) { 730 f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS); 731 if (f == null) { 732 throw new TimeoutException(); 733 } 734 long now = System.nanoTime(); 735 timeoutNanos -= now - lastTime; 736 lastTime = now; 737 } else { 738 f = futureQueue.take(); 739 } 740 } 741 if (f != null) { 742 --active; 743 try { 744 return f.get(); 745 } catch (ExecutionException eex) { 746 ee = eex; 747 } catch (InterruptedException iex) { 748 throw iex; 749 } catch (Exception rex) { // sneaky checked exception 750 ee = new ExecutionException(rex); 751 } 752 } 753 } 754 755 if (ee == null) { 756 ee = new ExecutionException(null); 757 } 758 throw ee; 759 } finally { 760 for (Future<T> f : futures) { 761 f.cancel(true); 762 } 763 } 764 } 765 766 /** 767 * Submits the task and adds a listener that adds the future to {@code queue} when it completes. 768 */ 769 @J2ktIncompatible 770 @GwtIncompatible // TODO 771 private static <T extends @Nullable Object> ListenableFuture<T> submitAndAddQueueListener( 772 ListeningExecutorService executorService, 773 Callable<T> task, 774 final BlockingQueue<Future<T>> queue) { 775 final ListenableFuture<T> future = executorService.submit(task); 776 future.addListener( 777 new Runnable() { 778 @Override 779 public void run() { 780 queue.add(future); 781 } 782 }, 783 directExecutor()); 784 return future; 785 } 786 787 /** 788 * Returns a default thread factory used to create new threads. 789 * 790 * <p>When running on AppEngine with access to <a 791 * href="https://cloud.google.com/appengine/docs/standard/java/javadoc/">AppEngine legacy 792 * APIs</a>, this method returns {@code ThreadManager.currentRequestThreadFactory()}. Otherwise, 793 * it returns {@link Executors#defaultThreadFactory()}. 794 * 795 * @since 14.0 796 */ 797 @J2ktIncompatible 798 @GwtIncompatible // concurrency 799 public static ThreadFactory platformThreadFactory() { 800 if (!isAppEngineWithApiClasses()) { 801 return Executors.defaultThreadFactory(); 802 } 803 try { 804 return (ThreadFactory) 805 Class.forName("com.google.appengine.api.ThreadManager") 806 .getMethod("currentRequestThreadFactory") 807 .invoke(null); 808 } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException e) { 809 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 810 } catch (InvocationTargetException e) { 811 throwIfUnchecked(e.getCause()); 812 // This should be impossible: `currentRequestThreadFactory` has no `throws` clause. 813 throw new UndeclaredThrowableException(e.getCause()); 814 } 815 } 816 817 @J2ktIncompatible 818 @GwtIncompatible // TODO 819 private static boolean isAppEngineWithApiClasses() { 820 if (System.getProperty("com.google.appengine.runtime.environment") == null) { 821 return false; 822 } 823 try { 824 Class.forName("com.google.appengine.api.utils.SystemProperty"); 825 } catch (ClassNotFoundException e) { 826 return false; 827 } 828 try { 829 // If the current environment is null, we're not inside AppEngine. 830 return Class.forName("com.google.apphosting.api.ApiProxy") 831 .getMethod("getCurrentEnvironment") 832 .invoke(null) 833 != null; 834 } catch (ClassNotFoundException e) { 835 // If ApiProxy doesn't exist, we're not on AppEngine at all. 836 return false; 837 } catch (InvocationTargetException e) { 838 // If ApiProxy throws an exception, we're not in a proper AppEngine environment. 839 return false; 840 } catch (IllegalAccessException e) { 841 // If the method isn't accessible, we're not on a supported version of AppEngine; 842 return false; 843 } catch (NoSuchMethodException e) { 844 // If the method doesn't exist, we're not on a supported version of AppEngine; 845 return false; 846 } 847 } 848 849 /** 850 * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless 851 * changing the name is forbidden by the security manager. 852 */ 853 @J2ktIncompatible 854 @GwtIncompatible // concurrency 855 static Thread newThread(String name, Runnable runnable) { 856 checkNotNull(name); 857 checkNotNull(runnable); 858 // TODO(b/139726489): Confirm that null is impossible here. 859 Thread result = requireNonNull(platformThreadFactory().newThread(runnable)); 860 try { 861 result.setName(name); 862 } catch (SecurityException e) { 863 // OK if we can't set the name in this environment. 864 } 865 return result; 866 } 867 868 // TODO(lukes): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService? 869 // TODO(lukes): provide overloads that take constant strings? Function<Runnable, String>s to 870 // calculate names? 871 872 /** 873 * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in. 874 * 875 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 876 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 877 * prevents the renaming then it will be skipped but the tasks will still execute. 878 * 879 * @param executor The executor to decorate 880 * @param nameSupplier The source of names for each task 881 */ 882 @J2ktIncompatible 883 @GwtIncompatible // concurrency 884 static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) { 885 checkNotNull(executor); 886 checkNotNull(nameSupplier); 887 return new Executor() { 888 @Override 889 public void execute(Runnable command) { 890 executor.execute(Callables.threadRenaming(command, nameSupplier)); 891 } 892 }; 893 } 894 895 /** 896 * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run 897 * in. 898 * 899 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 900 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 901 * prevents the renaming then it will be skipped but the tasks will still execute. 902 * 903 * @param service The executor to decorate 904 * @param nameSupplier The source of names for each task 905 */ 906 @J2ktIncompatible 907 @GwtIncompatible // concurrency 908 static ExecutorService renamingDecorator( 909 final ExecutorService service, final Supplier<String> nameSupplier) { 910 checkNotNull(service); 911 checkNotNull(nameSupplier); 912 return new WrappingExecutorService(service) { 913 @Override 914 protected <T extends @Nullable Object> Callable<T> wrapTask(Callable<T> callable) { 915 return Callables.threadRenaming(callable, nameSupplier); 916 } 917 918 @Override 919 protected Runnable wrapTask(Runnable command) { 920 return Callables.threadRenaming(command, nameSupplier); 921 } 922 }; 923 } 924 925 /** 926 * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its 927 * tasks run in. 928 * 929 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 930 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 931 * prevents the renaming then it will be skipped but the tasks will still execute. 932 * 933 * @param service The executor to decorate 934 * @param nameSupplier The source of names for each task 935 */ 936 @J2ktIncompatible 937 @GwtIncompatible // concurrency 938 static ScheduledExecutorService renamingDecorator( 939 final ScheduledExecutorService service, final Supplier<String> nameSupplier) { 940 checkNotNull(service); 941 checkNotNull(nameSupplier); 942 return new WrappingScheduledExecutorService(service) { 943 @Override 944 protected <T extends @Nullable Object> Callable<T> wrapTask(Callable<T> callable) { 945 return Callables.threadRenaming(callable, nameSupplier); 946 } 947 948 @Override 949 protected Runnable wrapTask(Runnable command) { 950 return Callables.threadRenaming(command, nameSupplier); 951 } 952 }; 953 } 954 955 /** 956 * Shuts down the given executor service gradually, first disabling new submissions and later, if 957 * necessary, cancelling remaining tasks. 958 * 959 * <p>The method takes the following steps: 960 * 961 * <ol> 962 * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. 963 * <li>awaits executor service termination for half of the specified timeout. 964 * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling 965 * pending tasks and interrupting running tasks. 966 * <li>awaits executor service termination for the other half of the specified timeout. 967 * </ol> 968 * 969 * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link 970 * ExecutorService#shutdownNow()} and returns. 971 * 972 * @param service the {@code ExecutorService} to shut down 973 * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate 974 * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} 975 * if the call timed out or was interrupted 976 * @since 28.0 (but only since 33.4.0 in the Android flavor) 977 */ 978 @CanIgnoreReturnValue 979 @J2ktIncompatible 980 @GwtIncompatible // java.time.Duration 981 public static boolean shutdownAndAwaitTermination(ExecutorService service, Duration timeout) { 982 return shutdownAndAwaitTermination(service, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); 983 } 984 985 /** 986 * Shuts down the given executor service gradually, first disabling new submissions and later, if 987 * necessary, cancelling remaining tasks. 988 * 989 * <p>The method takes the following steps: 990 * 991 * <ol> 992 * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. 993 * <li>awaits executor service termination for half of the specified timeout. 994 * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling 995 * pending tasks and interrupting running tasks. 996 * <li>awaits executor service termination for the other half of the specified timeout. 997 * </ol> 998 * 999 * <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link 1000 * ExecutorService#shutdownNow()} and returns. 1001 * 1002 * @param service the {@code ExecutorService} to shut down 1003 * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate 1004 * @param unit the time unit of the timeout argument 1005 * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} 1006 * if the call timed out or was interrupted 1007 * @since 17.0 1008 */ 1009 @CanIgnoreReturnValue 1010 @J2ktIncompatible 1011 @GwtIncompatible // concurrency 1012 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 1013 public static boolean shutdownAndAwaitTermination( 1014 ExecutorService service, long timeout, TimeUnit unit) { 1015 long halfTimeoutNanos = unit.toNanos(timeout) / 2; 1016 // Disable new tasks from being submitted 1017 service.shutdown(); 1018 try { 1019 // Wait for half the duration of the timeout for existing tasks to terminate 1020 if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { 1021 // Cancel currently executing tasks 1022 service.shutdownNow(); 1023 // Wait the other half of the timeout for tasks to respond to being cancelled 1024 service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); 1025 } 1026 } catch (InterruptedException ie) { 1027 // Preserve interrupt status 1028 Thread.currentThread().interrupt(); 1029 // (Re-)Cancel if current thread also interrupted 1030 service.shutdownNow(); 1031 } 1032 return service.isTerminated(); 1033 } 1034 1035 /** 1036 * Returns an Executor that will propagate {@link RejectedExecutionException} from the delegate 1037 * executor to the given {@code future}. 1038 * 1039 * <p>Note, the returned executor can only be used once. 1040 */ 1041 static Executor rejectionPropagatingExecutor( 1042 final Executor delegate, final AbstractFuture<?> future) { 1043 checkNotNull(delegate); 1044 checkNotNull(future); 1045 if (delegate == directExecutor()) { 1046 // directExecutor() cannot throw RejectedExecutionException 1047 return delegate; 1048 } 1049 return new Executor() { 1050 @Override 1051 public void execute(Runnable command) { 1052 try { 1053 delegate.execute(command); 1054 } catch (RejectedExecutionException e) { 1055 future.setException(e); 1056 } 1057 } 1058 }; 1059 } 1060}