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